[
  {
    "path": ".gitignore",
    "content": "/.stack-work\n/dist\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM ubuntu:xenial\n\nENV DEBIAN_FRONTEND noninteractive\nENV LD_LIBRARY_PATH /usr/local/lib\nENV PATH ${PATH}:/root/.local/bin\n\nRUN apt-get update\nRUN apt-get install -y asciidoc curl git libbz2-dev libncurses5-dev\n\n### Install Stack\nRUN mkdir -p /root/.local/bin\nRUN curl -sSL https://get.haskellstack.org | sh\n\n### Install Haste\nWORKDIR /tmp\nRUN git clone https://github.com/valderman/haste-compiler\nWORKDIR /tmp/haste-compiler\nRUN git checkout 0.6.0.0\nRUN printf '%s tagged-0.8.5\\n%s transformers-compat-0.5.1.4\\nsetup-info:\\n  ghc:\\n    linux64-nopie:\\n      7.10.3:\\n        url: \"https://github.com/commercialhaskell/ghc/releases/download/ghc-7.10.3-release/ghc-7.10.3-x86_64-deb8-linux.tar.xz\"\\n        content-length: 90852380\\n        sha1: bab16f95ef4fe6b7cc2fb6b36a02dceeeb53faa4\\n' '-' '-' >> stack.yaml\nRUN stack setup\nRUN stack install\nRUN stack install hsc2hs\nRUN stack exec haste-boot -- --force --local\n\n### Install Haste package manager\nWORKDIR /root/.haste/x86_64-linux-haste-0.6.0.0-ghc-7.10.3/haste-cabal\nRUN cp libgmp.so.3 ${LD_LIBRARY_PATH}\nRUN cp haste-cabal.bin /root/.local/bin/haste-cabal\n\n### Install Haste packages\nRUN haste-cabal install bimap parsec\n\n### Create workspace\nRUN mkdir /workspace\nWORKDIR /workspace\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "Makefile",
    "content": ".PHONY: all test clean\nall: dhcdemo.js dhcdemo.html\ndhcdemo.js: *.hs dhcdemo.lhs; hastec -Wall dhcdemo.lhs\ndhcdemo.html: dhcdemo.lhs; asciidoc dhcdemo.lhs\ntest:; ghc -O2 -Wall test/Main.hs && test/Main\nherotest:; ghc -O2 -Wall Hero/test/Main.hs && Hero/test/Main\nclean:; rm -rf *.hi *.jsmod *.o *.dyn_hi *.dyn_o\n"
  },
  {
    "path": "README.asciidoc",
    "content": "= Dfinity Haskell Compiler =\n\nDHC is a Haskell compiler that produces WebAssembly.\n\nIt accepts only a tiny subset of the language.\n\n== Live demo ==\n\nhttps://dhc.dfinity.org\n\n== Installation / Dependencies ==\n\nRun `nix build`.\n\n== Usage / Examples ==\n\nThe `dhc` program takes Haskell source on standard input and compiles it to\nWebAssembly on standard output. Two IO functions are defined:\n\n------------------------------------------------------------------------------\nputStr :: String -> IO ()\nputInt :: Int -> IO ()  -- `Int` means 64-bit integer.\n------------------------------------------------------------------------------\n\nwhich respectively call WebAssembly imports:\n\n------------------------------------------------------------------------------\nsystem.putStr (ptr : i32, len : i32)\nsystem.putInt (lo : i32, hi : i32)\n------------------------------------------------------------------------------\n\nIn `system.putInt`, we split the integer into 32-bit halves to make life easier\nfor JavaScript.\n\nThe `rundhc` tool can interpret the output of `dhc`. It expects the input\nWebAssembly binary to export a function named `main` that takes no arguments\nand returns no arguments.\n\nFor example:\n\n------------------------------------------------------------------------------\n$ echo 'public(main) main=putStr\"Hello, World!\\n\"' | ./dhc | ./rundhc\nHello, World!\n------------------------------------------------------------------------------\n\n== License ==\n\nhttp://dfinity.network[*(C) 2017 DFINITY STIFTUNG*].\n\nAll code and designs are open sourced under GPL V3.\n\nimage::https://user-images.githubusercontent.com/6457089/32753794-10f4cbc2-c883-11e7-8dcf-ff8088b38f9f.png[dfinity logo]\n"
  },
  {
    "path": "default.nix",
    "content": "{ pkgs ? import <nixpkgs> {}, compiler ? \"ghc822\" }:\nwith pkgs; let\n  drv = haskellPackages.callCabal2nix \"dhc\" ./. {};\nin if pkgs.lib.inNixShell \n  then stdenv.lib.overrideDerivation drv.env (oldAttrs : \n    {\n      nativeBuildInputs = oldAttrs.nativeBuildInputs ++ [ cabal-install stack ];\n    })\n  else drv\n"
  },
  {
    "path": "dhc/Main.hs",
    "content": "-- Takes Haskell source given on standard input and compiles it to\n-- WebAssembly which is dumped to standard output.\n\nimport qualified Data.ByteString as B\nimport Asm\nimport Demo\n\nmain :: IO ()\nmain = do\n  s <- getContents\n  case hsToWasm jsDemoBoost s of\n    Left err -> error err\n    Right bin -> B.putStr $ B.pack $ fromIntegral <$> bin\n"
  },
  {
    "path": "dhc.cabal",
    "content": "name:          dhc\nversion:       0.1.0\nsynopsis:      A Haskell compiler that produces WebAssembly.\nlicense:       GPL-3\ncopyright:     2017 DFINITY Stiftung.\ncategory:      Language\nhomepage:      https://github.com/dfinity/dhc\nbug-reports:   https://github.com/dfinity/dhc/issues\nbuild-type:    Simple\ncabal-version: >=1.10\n\nlibrary\n  build-depends:\n    base,\n    binary,\n    bytestring,\n    containers,\n    mtl,\n    parsec\n  default-language:\n    Haskell2010\n  hs-source-dirs:\n    src\n  exposed-modules:\n    Asm\n    Ast\n    Boost\n    DHC\n    Encode\n    Hero.Hero\n    Hero.HeroIO\n    Hero.Parse\n    Parse\n    Std\n    WasmOp\n  ghc-options:\n    -O2\n    -Wall\n\nexecutable dhc\n  default-language:\n    Haskell2010\n  hs-source-dirs:\n    dhc\n    other\n  main-is:\n    Main.hs\n  other-modules:\n    Demo\n  build-depends:\n    base,\n    binary,\n    bytestring,\n    containers,\n    dhc,\n    mtl,\n    parsec\n  ghc-options:\n   -O2\n   -Wall\n   -threaded\n\ntest-suite test\n  default-language:\n    Haskell2010\n  type: exitcode-stdio-1.0\n  hs-source-dirs:\n    test\n    other\n  main-is:\n    Main.hs\n  build-depends:\n    base,\n    binary,\n    bytestring,\n    containers,\n    dhc,\n    heredoc,\n    HUnit,\n    mtl,\n    parsec\n  other-modules:\n    Demo\n    SoloSyscall\n"
  },
  {
    "path": "other/Demo.hs",
    "content": "-- DHC Boost that provides 2 functions:\n--\n--   putStr :: String -> IO ()\n--   putInt :: Int -> IO ()\n--\n-- and expects the host to provide 2 syscalls:\n--\n--  system.putStr (pointer : I32, length : I32) -> ()\n--  system.putInt (n : I64) -> ()\n--\n-- The JavaScript edition expects a variant of system.putInt:\n--\n--  system.putInt (lo : I32, hi : I32) -> ()\nmodule Demo (demoBoost, jsDemoBoost) where\n\nimport Ast\nimport Boost\nimport WasmOp\n\nsp :: Int\nsp = 0\n\ndemoBoost :: Boost\ndemoBoost = Boost\n  [ ((\"system\", \"putStr\"), ([I32, I32], []))\n  , ((\"system\", \"putInt\"), ([I64], []))\n  ]\n  []\n  [ (\"putStr\", (TC \"String\" :-> io (TC \"()\"), putStrAsm))\n  , (\"putInt\", (TC \"Int\" :-> io (TC \"()\"),\n    [ Custom $ ReduceArgs 1\n    , Get_global sp  -- system.putInt [[sp + 4] + 8].64\n    , I32_load 2 4\n    , I64_load 3 8\n    , Custom $ CallSym \"system.putInt\"\n    , Get_global sp  -- sp = sp + 12\n    , I32_const 12\n    , I32_add\n    , Set_global sp\n    , Custom $ CallSym \"#nil42\"\n    , End\n    ]))\n  ]\n  []\n  where io = TApp (TC \"IO\")\n\n-- The JavaScript edition of the host splits an int64 into low and high 32-bit\n-- words, since current JavaScript engines lack support for 64-bit integers.\njsDemoBoost :: Boost\njsDemoBoost = Boost\n  [ ((\"system\", \"putStr\"), ([I32, I32], []))\n  , ((\"system\", \"putInt\"), ([I32, I32], []))\n  ]\n  []\n  [ (\"putStr\", (TC \"String\" :-> io (TC \"()\"), putStrAsm))\n  , (\"putInt\", (TC \"Int\" :-> io (TC \"()\"),\n    [ Custom $ ReduceArgs 1\n    , Get_global sp  -- system.putInt [[sp + 4] + 8] [[sp + 4] + 12]\n    , I32_load 2 4\n    , I32_load 2 8\n    , Get_global sp\n    , I32_load 2 4\n    , I32_load 2 12\n    , Custom $ CallSym \"system.putInt\"\n    , Get_global sp  -- sp = sp + 12\n    , I32_const 12\n    , I32_add\n    , Set_global sp\n    , Custom $ CallSym \"#nil42\"\n    , End\n    ]))\n  ]\n  []\n  where io = TApp (TC \"IO\")\n\nputStrAsm :: [QuasiWasm]\nputStrAsm =\n  [ Custom $ ReduceArgs 1\n  , Get_global sp  -- system.putStr ([[sp + 4] + 4] [[sp + 4] + 8]) [[sp + 4] + 12]\n  , I32_load 2 4\n  , I32_load 2 4\n  , Get_global sp\n  , I32_load 2 4\n  , I32_load 2 8\n  , I32_add\n  , Get_global sp\n  , I32_load 2 4\n  , I32_load 2 12\n  , Custom $ CallSym \"system.putStr\"\n  , Get_global sp  -- sp = sp + 12\n  , I32_const 12\n  , I32_add\n  , Set_global sp\n  , Custom $ CallSym \"#nil42\"\n  , End\n  ]\n"
  },
  {
    "path": "other/dhcdemo.lhs",
    "content": "= DHC Demo =\n\nThe following compiles Haskell to WebAssembly and runs it.\n\nOnly a tiny fragment of the language is supported. There is almost no syntax\nsugar.\n\nSystem calls:\n\n------------------------------------------------------------------------------\nputStr :: String -> IO ()\nputInt :: Int -> IO ()\n------------------------------------------------------------------------------\n\nThere is no garbage collection.\n\nhttps://github.com/dfinity/dhc[Source].\n\n[pass]\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n<script type=\"text/javascript\">\nvar dv;\nfunction load8(addr) { return dv.getUint8(addr); }\nfunction runWasmInts(a){WebAssembly.instantiate(new Uint8Array(a),\n{system:{putInt:(lo,hi) => { Haste.sysPutInt(lo,hi); },\nputStr:(a,n) => { Haste.sysPutStr(a,n) } }}).then(x => {\nexpo = x.instance.exports;\ndv = new DataView(expo.memory.buffer);\ndocument.getElementById('out').innerHTML =\"\";\nexpo['main']()});\n}\n\nfunction downloadWasm(arr) {\n  var blob = new Blob([new Uint8Array(arr)], {type: \"application/octet-stream\"});\n  var a = document.createElement('a');\n  a.style.display = 'none';\n  document.body.append(a);\n  var url = URL.createObjectURL(blob);\n  a.href = url;\n  a.download = \"a.wasm\";\n  a.click();\n  URL.revokeObjectURL(url);\n}\n</script>\n<script src=\"dhcdemo.js\">\n</script>\n<p><textarea id=\"src\" rows=\"25\" cols=\"80\">\ninclude::test/demo.hs[]\n</textarea></p>\n<button id=\"go\">Compile & Run!</button>\n<button id=\"get\">Download</button>\n<p><textarea id=\"asm\" readonly rows=\"5\" cols=\"80\">\n</textarea></p>\n<pre id=\"out\"></pre>\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n//////////////////////////////////////////////////////////////////////////////\n\\begin{code}\n{-# LANGUAGE OverloadedStrings #-}\nimport Control.Monad\nimport Data.Char\nimport Haste.DOM\nimport Haste.Events\nimport Haste.Foreign\nimport Asm\nimport Demo\n\nappend :: Elem -> String -> IO ()\nappend e s = do\n  v <- getProp e \"innerHTML\"\n  setProp e \"innerHTML\" $ v ++ s\n\nsysPutStr :: Elem -> Int -> Int -> IO ()\nsysPutStr e a n = append e =<< mapM (fmap chr . load8 . (a +)) [0..n - 1]\n  where load8 = ffi \"load8\" :: Int -> IO Int\n\nsysPutInt :: Elem -> Int -> Int -> IO ()\nsysPutInt e y x = append e $ case x of\n  0 -> show y ++ if y >= 0 then \"\" else\n    \" (unsigned = \" ++ show (fromIntegral y + b) ++ \")\"\n  _ -> show $ fromIntegral x * b + ((fromIntegral y + b) `mod` b)\n  where b = 2^(32 :: Int) :: Integer\n\nmain :: IO ()\nmain = withElems [\"src\", \"asm\", \"go\", \"get\", \"out\"] $ \\[src, asmEl, goB, getB, outE] -> do\n  export \"sysPutStr\" $ sysPutStr outE\n  export \"sysPutInt\" $ sysPutInt outE\n  let\n    go f = do\n      setProp asmEl \"value\" \"\"\n      s <- (\"public (main)\\n\" ++) <$> getProp src \"value\"\n      case hsToWasm jsDemoBoost s of\n        Left err -> setProp asmEl \"value\" err\n        Right asm -> do\n          setProp asmEl \"value\" $ show asm\n          f asm\n  void $ goB `onEvent` Click $ const $ go $ ffi \"runWasmInts\"\n  void $ getB `onEvent` Click $ const $ go $ ffi \"downloadWasm\"\n\n\\end{code}\n//////////////////////////////////////////////////////////////////////////////\n"
  },
  {
    "path": "src/Asm.hs",
    "content": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NamedFieldPuns #-}\n#ifdef __HASTE__\n{-# LANGUAGE PackageImports #-}\n#endif\nmodule Asm\n  ( hsToWasm\n  , Ins(..)\n  , WasmType(..)  -- Re-export from WasmOp.\n  , hsToIns\n  , hsToGMachine\n  , tpGlobalIndex\n  ) where\n\nimport Control.Arrow\n#ifdef __HASTE__\nimport \"mtl\" Control.Monad.State\nimport Data.Map.Strict (Map)\n#else\nimport Control.Monad.State\nimport Data.ByteString.Short (ShortByteString, unpack)\nimport qualified Data.ByteString.Short as SBS\nimport Data.Map.Strict (Map, restrictKeys)\nimport Data.Semigroup ()\n#endif\nimport Data.Bits\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as S\n\nimport Boost\nimport DHC\nimport Encode\nimport Std\nimport WasmOp\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n#ifdef __HASTE__\nsbslen :: String -> Int\nsbslen = length\nunpack :: String -> [Int]\nunpack = fmap ord\ntype ShortByteString = String\nrestrictKeys :: Ord k => Map k a -> Set k -> Map k a\nrestrictKeys m s = M.filterWithKey (\\k _ -> S.member k s) m\n#else\nsbslen :: ShortByteString -> Int\nsbslen = SBS.length\n#endif\n\n-- | G-Machine instructions.\ndata Ins = Copro Int Int | PushInt Int64 | Push Int | PushGlobal String\n  | PushRef Int32\n  | PushString ShortByteString\n  | MkAp | Slide Int | Split Int | Eval\n  | UpdatePopEval Int | UpdateInd Int | Alloc Int\n  | Casejump [(Maybe Int, [Ins])] | Trap\n  | PushCallIndirect [Type]\n  | WasmPush [Ins] Type\n  | WasmCallIndirect [Type]\n  deriving Show\n\nnPages :: Int\nnPages = 8\n\ndata WasmMeta = WasmMeta\n  -- Arity of each user-defined function, whether exported or not.\n  -- Eval uses this to remove the spine correctly.\n  { arities :: Map String Int\n  -- Public and private functions that can become references.\n  -- We also hang on to the type of each argument as well as a function\n  -- to decode it from a heap object.\n  , exports :: [(String, [(Type, [Ins])])]\n  , elements :: [(String, [(Type, [Ins])])]\n  , callTypes :: [[Type]]  -- Types needed by call_indirect ops.\n  , strEndHP :: Int  -- Heap address immediately past the string constants.\n  , strAddrs :: Map ShortByteString Int  -- String constant addresses.\n  , storeTypes :: [Type]  -- Global store types.\n  , callEncoders :: Map String [Ins]  -- Helpers for call_indirect that encode messages.\n  }\n\nhsToGMachine :: Boost -> String -> Either String (Map String Int, Map String [Ins])\nhsToGMachine boost hs = first arities <$> hsToIns boost hs\n\nhsToWasm :: Boost -> String -> Either String [Int]\nhsToWasm boost s = insToBin s b . astToIns <$> hsToAst b qq s where\n  b = stdBoost <> boost\n  qq \"here\" h = Right h\n  qq \"wasmFromFile\" fileName = do\n    let prog = unsafePerformIO (readFile fileName)\n    case hsToWasm boost prog of\n        Left err -> Left err\n        Right ints -> Right $ chr <$> ints\n  qq \"wasm\" prog = case hsToWasm boost prog of\n    Left err -> Left err\n    Right ints -> Right $ chr <$> ints\n  qq scheme _ = Left $ \"hsToWasm: bad scheme: \" ++ scheme\n\nhsToIns :: Boost -> String -> Either String (WasmMeta, Map String [Ins])\nhsToIns boost s = astToIns <$> hsToAst (stdBoost <> boost) qq s where\n  qq \"here\" h = Right h\n  qq scheme _ = Left $ \"hsToIns: bad scheme: \" ++ scheme\n\ndata CompilerState = CompilerState\n  -- Bindings are local. They start empty and finish empty.\n  -- During compilation, they hold the stack position of the bound variables.\n  { bindings :: [(String, Int)]\n  -- Each call_indirect indexes into the type section of the binary.\n  -- We record the types used by the binary so we can collect and look them\n  -- up when generating assembly.\n  -- TODO: It'd be better to fold over CompilerState during compile to\n  -- incrementally update these fields.\n  , callIndirectTypes :: [[Type]]\n  , stringConstants :: [ShortByteString]\n  -- Compilation may generate auxiliary helpers.\n  , helpers :: [(String, [Ins])]\n  }\n\nalign4 :: Int -> Int\nalign4 n = (n + 3) `div` 4 * 4\n\nmkStrConsts :: [ShortByteString] -> (Int, Map ShortByteString Int)\nmkStrConsts = f (0, []) where\n  f (p, ds) [] = (p, M.fromList ds)\n  f (k, ds) (s:rest) = f (k + 16 + align4 (sbslen s), (s, k):ds) rest\n\nastToIns :: Clay -> (WasmMeta, Map String [Ins])\nastToIns cl = (WasmMeta\n  { arities = funs\n  , exports = compileDecoders <$> publics cl\n  , elements = compileDecoders <$> secrets cl\n  , callTypes = ciTypes\n  , strEndHP = hp1\n  , strAddrs = addrs\n  , storeTypes = snd <$> stores cl\n  , callEncoders = M.fromList $ concatMap helpers cs\n  }, fst <$> compilerOut) where\n  compilerOut = compile (fst <$> stores cl) <$> supers cl\n  cs = snd <$> M.elems compilerOut\n  ciTypes = foldl' union [] $ callIndirectTypes <$> cs\n  (hp1, addrs) = mkStrConsts $ nub $ concatMap stringConstants cs\n  funs = M.union ((\\(Ast (Lam as _)) -> length as) <$> supers cl) $\n    M.fromList $ concatMap (\\n -> [(\"#set-\" ++ show n, 1), (\"#get-\" ++ show n, 0)]) [0..length (stores cl) - 1]\n  -- Argument decoders only use a certain subset of functions.\n  compileDecoders = second $ fmap $ second (fst . compile [])\n\ntoDfnType :: Type -> WasmType\ntoDfnType t = case t of\n  TApp (TC \"()\") _ -> Ref \"Elem\"\n  TApp (TC \"[]\") _ -> Ref \"Elem\"\n  TC \"()\" -> Ref \"Elem\"\n  TC \"Int\" -> I64\n  TC \"I32\" -> I32\n  TC \"Bool\" -> I32\n  TC \"String\" -> Ref \"Databuf\"\n  TC s | elem s [\"Port\", \"Databuf\", \"Actor\", \"Module\"] -> Ref s\n  _ -> error $ \"BUG! type check failed to catch: \" ++ show t\n\nfollowGCalls :: [String] -> Set String -> Map String [Ins] -> Set String\nfollowGCalls fs prims m = execState (go fs) $ S.fromList fs where\n  go (f:rest) = if S.member f prims\n    then modify $ S.insert f\n    else do\n      maybe (pure ()) tr $ M.lookup f m\n      go rest\n  go [] = pure ()\n  tr (w:rest) = do\n    case w of\n      PushGlobal v -> do\n        s <- get\n        when (S.notMember v s) $ do\n          put $ S.insert v s\n          go [v]\n      PushCallIndirect ty -> go [show ty]\n      WasmPush enc _ -> tr enc\n      Casejump alts -> mapM_ tr $ snd <$> alts\n      _ -> pure ()\n    tr rest\n  tr [] = pure ()\n\n-- | Join two i32s into a single i64.\nmk64 :: Int -> Int -> Int64\nmk64 a b = fromIntegral a + shift (fromIntegral b) 32\n\ninsToBin :: String -> Boost -> (WasmMeta, Map String [Ins]) -> [Int]\ninsToBin src boost@(Boost imps _ _ boostFuns) (wm@WasmMeta {exports, elements, strAddrs, storeTypes}, gmachine) = wasm where\n  wasm = encodeWasm ProtoWasm\n    { sectImports = imps\n    , sectFunctions = snd <$> wasmFuns\n    , tableSize = 256\n    , sectGlobals =  -- Global section (1 = mutable).\n      [ [encType I32, 1, 0x41] ++ sleb128 memTop ++ [0xb]  -- SP\n      , [encType I32, 1, 0x41] ++ sleb128 (strEndHP wm) ++ [0xb]  -- HP\n      , [encType I32, 1, 0x41, 0, 0xb]  -- BP\n      , [encType I32, 1, 0x41] ++ sleb128 (length ees) ++ [0xb]  -- TP\n      ]\n      -- Global stores.\n      -- First one records if `main` has been run yet.\n      ++ map declareGlobal (TC \"I32\":storeTypes)\n    , sectExports = [(s, wasmFunNo ('@':s)) | (s, _) <- exports]\n    , sectElements = [(0, wasmFunNo . ('@':) . fst <$> ees)]\n    , sectDfn = ((wasmFunNo . ('@':)) *** map (toDfnType . fst)) <$> ees\n    , sectPersist = zip [mainCalled..] $ toDfnType <$> TC \"I32\":storeTypes\n    , sectsGeneric =\n      [ (5, [0 : leb128 nPages])  -- Memory section (0 = no-maximum).\n      , (11, encStrConsts <$> M.assocs strAddrs)  -- Data section.\n      ]\n    , sectsCustom =\n      [ (\"dfndbg\", [ord <$> show (sort $ swp <$> M.assocs wasmFunMap)])\n      , (\"dfnhs\", [ord <$> src])\n      ]\n    }\n  ees = exports ++ elements\n  declareGlobal (TC \"Int\") = [encType I64, 1, 0x42, 0, 0xb]\n  declareGlobal _ = [encType I32, 1, 0x41, 0, 0xb]\n  swp (a, b) = (b, a)\n  memTop = 65536*nPages - 4\n  encStrConsts (s, offset) = concat\n    [ [0, 0x41] ++ sleb128 offset ++ [0xb]\n    , leb128 $ 16 + sbslen s\n    , [fromEnum TagString, 0, 0, 0]\n    , enc32 $ offset + 16\n    , enc32 0\n    , enc32 $ sbslen s\n    , fromIntegral <$> unpack s\n    ]\n  -- Returns arity and 0-indexed number of given global function.\n  getGlobal s = case M.lookup s $ M.insert \"main\" 0 $ arities wm of\n    Just arity -> (arity, wasmFunNo s - firstPrim)\n    Nothing -> (arityFromType $ fromMaybe (error $ \"BUG! bad global: \" ++ s) $ M.lookup s primsType, wasmFunNo s - firstPrim)\n  firstPrim = wasmFunNo $ fst $ head evalFuns\n  cdq = concatMap deQuasi\n  internalFuns =\n    [ (\"#eval\", (([], []), evalAsm))\n    , (\"#mkap\", (([], []), mkApAsm))\n    , (\"#push32\", (([I32], []), push32Asm))  -- Low-level push.\n    , (\"#pushint\", (([I64], []), cdq pushIntAsm))\n    , (\"#pushref\", (([I32], []), cdq pushRefAsm))\n    , (\"#pushglobal\", (([I64], []), cdq pushGlobalAsm))\n    , (\"#updatepopeval\", (([I32], []), cdq updatePopEvalAsm))\n    , (\"#updateind\", (([I32], []), updateIndAsm))\n    , (\"#alloc\", (([I32], []), cdq allocAsm))\n    , (\"#pairwith42\", (([I32], []), pairWith42Asm))\n    , (\"#nil42\", (([], []), cdq nil42Asm))\n    ] ++ (second (second cdq) <$> boostFuns)\n  noInOut = ([], []) :: ([WasmType], [WasmType])\n  wasmFuns :: [(String, WasmFun)]\n  wasmFuns =\n    (second (\\((ins, outs), a) -> WasmFun (ins, outs) [] a) <$> internalFuns)\n    ++ evalFuns\n    -- Wrappers for functions in \"public\" and \"secret\" section.\n    ++ (wrap <$> ees)\n  evalFuns = concat  -- Functions that \"#eval\" can call.\n    -- Primitive functions.\n    -- The assembly for \"#eval\" requires that the primitive functions\n    -- directly precede those defined in the program.\n    [ M.assocs $ WasmFun noInOut [] . cdq . snd <$> livePrims\n    -- Global get and set functions that interact with the DHC stack.\n    , concat (zipWith mkStoreAsm storeTypes [0..])\n    -- Functions from the program, except `main`.\n    , M.assocs $ fromGMachine <$> M.delete \"main\" liveGs\n    -- The `main` function. Any supplied `main` function is appended to\n    -- some standard setup code.\n    , [(\"main\", WasmFun noInOut [] $ preMainAsm ++ concatMap fromIns (fromMaybe [] $ M.lookup \"main\" liveGs) ++ [End])]\n    -- Wrappers for call_indirect ops.\n    , M.assocs $ WasmFun noInOut [] . (++ [End]) . concatMap fromIns <$> callEncoders wm\n    ]\n\n  -- The \"***\" is a hack to force it to follow the instructions for all\n  -- argument encoders and decoders.\n  liveGIds = followGCalls (\"***\":\"main\":(fst <$> ees)) (M.keysSet prims) $ gmachine `M.union` M.singleton \"***\" (concatMap snd (concatMap snd ees) ++ concat (M.elems $ callEncoders wm))\n  liveGs = restrictKeys gmachine liveGIds\n  livePrims = restrictKeys prims liveGIds\n\n  fromGMachine g = WasmFun noInOut [] $ (++ [End]) $ concatMap fromIns g\n  preMainAsm =\n    [ I32_const 1  -- mainCalled = 1\n    , Set_global mainCalled\n    ]\n  wasmFunMap = M.fromList $ zip (((\\(m, f) -> m ++ \".\" ++ f) . fst <$> imps) ++ (fst <$> wasmFuns)) [0..]\n  wasmFunNo s = fromMaybe (error s) $ M.lookup s wasmFunMap\n\n  wrap (f, ps) = let (inTypes, decoders) = unzip ps in\n    (,) ('@':f) $ WasmFun (toWasmType <$> inTypes, []) [] $\n    -- Wraps a DHC function.\n    -- When a wasm function f(arg0, arg1, ...) is called,\n    -- the arguments are placed in local variables.\n    -- This wrapper builds:\n    --\n    --   f :@ arg0 :@ arg 1 :@ ... :@ #RealWorld\n    --\n    -- on the heap, places a pointer to this on the stack, then calls Eval.\n    --\n    -- Additionally, for each non-`main` function, first call `main`\n    -- if a certain global flag is false.\n    -- The `main` function always exists and sets this global flag.\n    (if f /= \"main\" then\n    [ Get_global mainCalled  -- if (!mainCalled) mainCalled = 1, main;\n    , I32_eqz\n    , If Nada (\n      [ I32_const $ fromIntegral memTop  -- sp = top of memory\n      , Set_global sp\n      , I32_const 42  -- #push32 42\n      , Call $ wasmFunNo \"#push32\"\n      ] ++ concatMap fromIns [PushGlobal \"main\", MkAp, Eval]) []\n    ]\n    else []) ++\n\n    [ I32_const $ fromIntegral memTop  -- sp = top of memory\n    , Set_global sp\n    , I32_const 42  -- #push32 42\n    , Call $ wasmFunNo \"#push32\"\n    ] ++\n    -- Input arguments are local variables.\n    -- We move these to our stack in reverse order.\n    concat (reverse $ zipWith3 fromWire inTypes decoders [0..]) ++\n    -- Build the spine.\n    concatMap fromIns (PushGlobal f : replicate (length inTypes + 1) MkAp) ++\n    [ Call $ wasmFunNo \"#eval\"\n    , End\n    ]\n  fromWire t dec i =\n    [ Get_local i\n    , case toWasmType t of\n      I64 -> Call $ wasmFunNo \"#pushint\"\n      _   -> Call $ wasmFunNo \"#pushref\"\n    ] ++ concatMap fromIns dec ++\n    [ Call $ wasmFunNo \"#mkap\" ]\n  evalAsm =\n    [ Block Nada\n      [ Loop Nada\n        [ Get_global sp  -- bp = [sp + 4]\n        , I32_load 2 4\n        , Set_global bp\n        , Block Nada\n          [ Block Nada\n            [ Get_global bp\n            , I32_load8_u 0 0\n            , Br_table [0, 1, 3] 4  -- case [bp].8u; branch on Tag\n            ]  -- 0: Ap\n          , Get_global bp  -- #push32 [bp + 8]\n          , I32_load 2 8\n          , Call $ wasmFunNo \"#push32\"\n          , Br 1\n          ]  -- 1: Ind.\n        , Get_global sp  -- [sp + 4] = [bp + 4]\n        , Get_global bp\n        , I32_load 2 4\n        , I32_store 2 4\n        , Br 0\n        ]  -- 2: Eval loop.\n      ]  -- 3: Global\n    , Get_global bp  -- save bp, sp\n    , Get_global sp\n    , Get_global sp  -- bp = sp + 4 + 4 * ([bp].16u >> 8)\n    , I32_const 4\n    , I32_add\n    , Get_global bp\n    , I32_load16_u 1 0\n    , I32_const 8\n    , I32_shr_u\n    , I32_const 4\n    , I32_mul\n    , I32_add\n    , Set_global bp\n\n    , Loop Nada  -- Remove spine.\n      [ Get_global sp  -- sp = sp + 4\n      , I32_const 4\n      , I32_add\n      , Set_global sp\n      , Get_global sp  -- if sp /= bp then\n      , Get_global bp\n      , I32_ne\n      , If Nada\n        [ Get_global sp  -- [sp] = [[sp + 4] + 12]\n        , Get_global sp\n        , I32_load 2 4\n        , I32_load 2 12\n        , I32_store 2 0\n        , Br 1\n        ] []  -- If\n      ]  -- Loop\n    , Set_global sp  -- restore bp, sp\n    , Set_global bp\n    ] ++ nest n ++ [End]\n    where\n      -- Eval functions are resolved in a giant `br_table`. This is ugly, but\n      -- avoids run-time type-checking.\n      n = length evalFuns\n      nest 0 =\n        [ Get_global bp  -- case [bp + 4]\n        , I32_load 2 4\n        , Br_table [0..n-1] n\n        ]\n      nest k = [Block Nada $ nest $ k - 1, Call $ firstPrim + k - 1, Return]\n\n  mkStoreAsm :: Type -> Int -> [(String, WasmFun)]\n  mkStoreAsm t n =\n    [ (\"#set-\" ++ show n, WasmFun noInOut [] $\n      [ Get_global sp  -- Push 0, Eval.\n      , I32_load 2 4\n      , Call $ wasmFunNo \"#push32\"\n      , Call $ wasmFunNo \"#eval\"\n      ] ++ (case t of\n        TC \"Int\" ->\n          [ Get_global sp  -- Set_global n [[sp + 4] + 8].64\n          , I32_load 2 4\n          , I64_load 3 8\n          , Set_global $ storeOffset + n\n          ]\n        _ ->\n          [ Get_global sp  -- Set_global n [[sp + 4] + 4]\n          , I32_load 2 4\n          , I32_load 2 4\n          , Set_global $ storeOffset + n\n          ]\n      ) ++\n      [ Get_global sp  -- sp = sp + 12\n      , I32_const 12\n      , I32_add\n      , Set_global sp\n      , Call $ wasmFunNo \"#nil42\"\n      , End\n      ])\n    , (\"#get-\" ++ show n, WasmFun noInOut [] $\n      [ Get_global hp  -- PUSH hp\n      ] ++ (case t of\n        TC \"Int\" ->\n          [ Get_global hp  -- [hp] = TagInt\n          , tag_const TagInt\n          , I32_store 2 0\n          , Get_global hp  -- [hp + 8] = Get_global n\n          , Get_global $ storeOffset + n\n          , I64_store 3 8\n          , Get_global hp  -- hp = hp + 16\n          , I32_const 16\n          , I32_add\n          , Set_global hp\n          ]\n        _ ->\n          [ Get_global hp  -- [hp] = TagRef\n          , tag_const TagRef\n          , I32_store 2 0\n          , Get_global hp  -- [hp + 4] = Get_global n\n          , Get_global $ storeOffset + n\n          , I32_store 2 4\n          , Get_global hp  -- hp = hp + 8\n          , I32_const 8\n          , I32_add\n          , Set_global hp\n          ]\n      ) ++\n      [ Get_global sp  -- sp = sp + 4\n      , I32_const 4\n      , I32_add\n      , Set_global sp\n      , Call $ wasmFunNo \"#pairwith42\"\n      , End\n      ])\n    ]\n  deQuasi :: QuasiWasm -> [WasmOp]\n  deQuasi (Custom x) = case x of\n    CallSym s -> [Call $ wasmFunNo s]\n    ReduceArgs n -> concat $ replicate n $ concatMap fromIns [Push (n - 1), Eval]\n\n  deQuasi (Block t body) = [Block t $ cdq body]\n  deQuasi (Loop  t body) = [Loop  t $ cdq body]\n  deQuasi (If    t a b)  = [If    t (cdq a) $ cdq b]\n  deQuasi op = [error \"missing deQuasi case?\" <$> op]\n\n  prims = M.fromList $ boostPrims boost\n  primsType = fst <$> prims\n\n  fromIns :: Ins -> [WasmOp]\n  fromIns instruction = case instruction of\n    Trap -> [ Unreachable ]\n    Eval -> [ Call $ wasmFunNo \"#eval\" ]  -- (Tail call.)\n    PushInt n -> [ I64_const n, Call $ wasmFunNo \"#pushint\" ]\n    PushRef n -> [ I32_const n, Call $ wasmFunNo \"#pushref\" ]\n    Push n ->\n      [ Get_global sp\n      , I32_load 2 $ fromIntegral $ 4*(n + 1)\n      , Call $ wasmFunNo \"#push32\"\n      ]\n    MkAp -> [ Call $ wasmFunNo \"#mkap\" ]\n    PushGlobal fun | (n, g) <- getGlobal fun ->\n      [ I64_const $ mk64 (fromEnum TagGlobal + shift n 8) g\n      , Call $ wasmFunNo \"#pushglobal\"\n      ]\n    PushString s ->\n      -- #push32 (address of string const)\n      [ I32_const $ fromIntegral $ strAddrs M.! s\n      , Call $ wasmFunNo \"#push32\"\n      ]\n    PushCallIndirect ty ->\n      -- 3 arguments: slot, argument tuple, #RealWorld.\n      [ I64_const $ mk64 (fromEnum TagGlobal + shift 3 8) $ wasmFunNo (show ty) - firstPrim\n      , Call $ wasmFunNo \"#pushglobal\"\n      ]\n    Slide 0 -> []\n    Slide n ->\n      [ Get_global sp  -- [sp + 4*(n + 1)] = [sp + 4]\n      , Get_global sp\n      , I32_load 2 4\n      , I32_store 2 $ 4*(fromIntegral n + 1)\n      , Get_global sp  -- sp = sp + 4*n\n      , I32_const $ 4*fromIntegral n\n      , I32_add\n      , Set_global sp\n      ]\n    Alloc n -> [ I32_const $ fromIntegral n, Call $ wasmFunNo \"#alloc\" ]\n    UpdateInd n ->\n      [ I32_const $ fromIntegral $ 4*(n + 1), Call $ wasmFunNo \"#updateind\" ]\n    UpdatePopEval n ->\n      [ I32_const $ fromIntegral $ 4*(n + 1)\n      , Call $ wasmFunNo \"#updatepopeval\"\n      ]\n    Copro m n ->\n      [ Get_global hp  -- [hp] = (TagSum | (n << 8) | (m << 32)).64\n      , I64_const $ mk64 (fromEnum TagSum + shift n 8) m\n      , I64_store 3 0\n      ] ++ concat [\n        [ Get_global hp  -- [hp + 4 + 4*i] = [sp + 4*i]\n        , Get_global sp\n        , I32_load 2 $ fromIntegral $ 4*i\n        , I32_store 2 $ fromIntegral $ 4 + 4*i\n        ] | i <- [1..n]] ++\n      [ Get_global sp  -- sp = sp + 4*n\n      , I32_const $ fromIntegral $ 4*n - 4\n      , I32_add\n      , Set_global sp\n      , Get_global sp  -- [sp + 4] = hp\n      , Get_global hp\n      , I32_store 2 4\n      , Get_global hp  -- hp = hp + 8 + ceil(n / 2) * 8\n      , I32_const $ fromIntegral $ 8 + 8 * ((n + 1) `div` 2)\n      , I32_add\n      , Set_global hp\n      ]\n    Casejump alts0 -> let\n      (underscore, unsortedAlts) = partition (isNothing . fst) alts0\n      alts = sortOn fst unsortedAlts\n      catchall = if null underscore then [Trap] else snd $ head underscore\n      tab = zip (fromJust . fst <$> alts) [0..]\n      m = maximum $ fromJust . fst <$> alts\n      nest j (ins:rest) = pure $ Block Nada $ nest (j + 1) rest ++ concatMap fromIns ins ++ [Br j]\n      nest _ [] = pure $ Block Nada\n        [ Get_global bp  -- Br_table [bp + 4]\n        , I32_load 2 4\n        , Br_table [fromIntegral $ fromMaybe (length alts) $ lookup i tab | i <- [0..m]] $ m + 1\n        ]\n      in if null alts then concatMap fromIns catchall else\n      -- [sp + 4] should be:\n      -- 0: TagSum\n      -- 4: \"Enum\"\n      -- 8, 12, ...: fields\n      [ Get_global sp  -- bp = [sp + 4]\n      , I32_load 2 4\n      , Set_global bp\n      , Block Nada $ nest 1 (reverse $ snd <$> alts) ++ concatMap fromIns catchall\n      ]\n\n    Split 0 -> [Get_global sp, I32_const 4, I32_add, Set_global sp]\n    Split n ->\n      [ Get_global sp  -- bp = [sp + 4]\n      , I32_load 2 4\n      , Set_global bp\n      , Get_global sp  -- sp = sp - 4*(n - 1)\n      , I32_const $ fromIntegral $ 4*(n - 1)\n      , I32_sub\n      , Set_global sp\n      ] ++ concat [\n        [ Get_global sp  -- [sp + 4*i] = [bp + 4 + 4*i]\n        , Get_global bp\n        , I32_load 2 $ fromIntegral $ 4 + 4*i\n        , I32_store 2 $ fromIntegral $ 4*i\n        ] | i <- [1..n]]\n    WasmPush encoder (TC \"Int\") ->\n      concatMap fromIns (encoder ++ [MkAp, Eval]) ++\n      [ Get_global sp  -- PUSH [[sp + 4] + 8].64\n      , I32_load 2 4\n      , I64_load 3 8\n      , Get_global sp  -- sp = sp + 4\n      , I32_const 4\n      , I32_add\n      , Set_global sp\n      ]\n    WasmPush encoder _ ->\n      concatMap fromIns (encoder ++ [MkAp, Eval]) ++\n      [ Get_global sp  -- PUSH [[sp + 4] + 4]\n      , I32_load 2 4\n      , I32_load 2 4\n      , Get_global sp  -- sp = sp + 4\n      , I32_const 4\n      , I32_add\n      , Set_global sp\n      ]\n    WasmCallIndirect inTypes ->\n      -- 3 arguments: slot, argument tuple, #RealWorld.\n      -- Assumes all message arguments have already been pushed.\n      [ Get_global sp  -- PUSH [[sp + 4] + 4]\n      , I32_load 2 4\n      , I32_load 2 4\n      , Call_indirect (toWasmType <$> inTypes, [])\n      , Get_global sp  -- sp = sp + 16\n      , I32_const 16\n      , I32_add\n      , Set_global sp\n      , Call $ wasmFunNo \"#nil42\"\n      ]\n\nsp, hp, bp, tpGlobalIndex, mainCalled, storeOffset :: Int\n[sp, hp, bp, tpGlobalIndex, mainCalled, storeOffset] = [0..5]\n\ncompile :: [String] -> Ast -> ([Ins], CompilerState)\ncompile ps d = runState (mk1 ps d) $ CompilerState [] [] [] []\n\nmk1 :: [String] -> Ast -> State CompilerState [Ins]\nmk1 pglobals (Ast ast) = case ast of\n  -- Thanks to lambda lifting, `Lam` can only occur at the top level.\n  Lam as b -> do\n    putBindings $ zip as [0..]\n    (++ [UpdatePopEval $ length as]) <$> rec b\n  I n -> pure [PushInt n]\n  S s -> do\n    st <- get\n    put st { stringConstants = s:stringConstants st }\n    pure [PushString s]\n  t :@ u -> do\n    mu <- rec u\n    bump 1\n    mt <- rec t\n    bump (-1)\n    pure $ case last mt of\n      Copro _ _ -> mu ++ mt\n      _ -> concat [mu, mt, [MkAp]]\n  CallSlot ty encoders -> do\n    st <- get\n    put st { callIndirectTypes = callIndirectTypes st `union` [ty] }\n    ms <- forM encoders rec\n    addHelper ty ms\n    pure [PushCallIndirect ty]\n  Var v -> do\n    m <- getBindings\n    pure $ case lookup v m of\n      Just k -> [Push k]\n      _ | Just i <- elemIndex v pglobals ->\n        -- Stores become (set n, get n) tuples.\n        [ PushGlobal $ \"#get-\" ++ show i\n        , PushGlobal $ \"#set-\" ++ show i\n        , Copro 0 2\n        ]\n      _ -> [PushGlobal v]\n  Pack n m -> pure [Copro n m]\n  Cas expr alts -> do\n    me <- rec expr\n    xs <- forM alts $ \\(p, body) -> do\n      orig <- getBindings\n      (f, b) <- case fromApList p of\n        (Ast (Pack n _):vs) -> do\n          bump $ length vs\n          modifyBindings (zip (map (\\(Ast (Var v)) -> v) vs) [0..] ++)\n          bod <- rec body\n          pure (Just $ fromIntegral n, Split (length vs) : bod ++ [Slide (length vs)])\n        [Ast (Var s)] -> do\n          bump 1\n          modifyBindings ((s, 0):)\n          (,) Nothing . (++ [Slide 1]) <$> rec body\n        _ -> undefined\n      putBindings orig\n      pure (f, b)\n    pure $ me ++ [Eval, Casejump xs]\n  Let ds body -> let n = length ds in do\n    orig <- getBindings\n    bump n\n    modifyBindings (zip (fst <$> ds) [n-1,n-2..0] ++)\n    dsAsm <- mapM rec $ snd <$> ds\n    b <- rec body\n    putBindings orig\n    pure $ Alloc n : concat (zipWith (++) dsAsm (pure . UpdateInd <$> [n-1,n-2..0])) ++ b ++ [Slide n]\n  DictIndex n -> pure [PushRef $ fromIntegral $ 4*n + 8, PushGlobal \"#rundict\", MkAp]\n  _ -> error $ \"TODO: compile: \" ++ show ast\n  where\n    bump n = modifyBindings $ fmap $ second (+n)\n    modifyBindings f = putBindings =<< f <$> getBindings\n    getBindings = gets bindings\n    putBindings b = do\n      st <- get\n      put st { bindings = b }\n    rec = mk1 pglobals\n\nfromApList :: Ast -> [Ast]\nfromApList (Ast (a :@ b)) = fromApList a ++ [b]\nfromApList a = [a]\n\nmkApAsm :: [WasmOp]\nmkApAsm =\n  [ Get_global hp  -- [hp] = TagAp\n  , tag_const TagAp\n  , I32_store 2 0\n  , Get_global hp  -- [hp + 8] = [sp + 4]\n  , Get_global sp\n  , I32_load 2 4\n  , I32_store 2 8\n  , Get_global hp  -- [hp + 12] = [sp + 8]\n  , Get_global sp\n  , I32_load 2 8\n  , I32_store 2 12\n  , Get_global sp  -- [sp + 8] = hp\n  , Get_global hp\n  , I32_store 2 8\n  , Get_global sp  -- sp = sp + 4\n  , I32_const 4\n  , I32_add\n  , Set_global sp\n  , Get_global hp  -- hp = hp + 16\n  , I32_const 16\n  , I32_add\n  , Set_global hp\n  , End\n  ]\npush32Asm :: [WasmOp]\npush32Asm =\n  [ Get_global sp  -- [sp] = local_0\n  , Get_local 0\n  , I32_store 2 0\n  , Get_global sp  -- sp = sp - 4\n  , I32_const 4\n  , I32_sub\n  , Set_global sp\n  , End\n  ]\npushIntAsm :: [QuasiWasm]\npushIntAsm =\n  [ Get_global hp  -- #push32 hp\n  , Custom $ CallSym \"#push32\"\n  , Get_global hp  -- [hp] = TagInt\n  , tag_const TagInt\n  , I32_store 2 0\n  , Get_global hp  -- [hp + 8] = local_0\n  , Get_local 0\n  , I64_store 3 8\n  , Get_global hp  -- hp = hp + 16\n  , I32_const 16\n  , I32_add\n  , Set_global hp\n  , End\n  ]\npushRefAsm :: [QuasiWasm]\npushRefAsm =\n  [ Get_global hp  -- #push32 hp\n  , Custom $ CallSym \"#push32\"\n  , Get_global hp  -- [hp] = TagRef\n  , tag_const TagRef\n  , I32_store 2 0\n  , Get_global hp  -- [hp + 4] = local_0\n  , Get_local 0\n  , I32_store 2 4\n  , Get_global hp  -- hp = hp + 8\n  , I32_const 8\n  , I32_add\n  , Set_global hp\n  , End\n  ]\npushGlobalAsm :: [QuasiWasm]\npushGlobalAsm =\n  [ Get_global hp  -- #push32 hp\n  , Custom $ CallSym \"#push32\"\n  , Get_global hp  -- [hp] = local_0.64  -- TagGlobal | (n << 8) | (funNo << 32)\n  , Get_local 0\n  , I64_store 3 0\n  , Get_global hp  -- hp = hp + 8\n  , I32_const 8\n  , I32_add\n  , Set_global hp\n  , End\n  ]\nupdatePopEvalAsm :: [QuasiWasm]\nupdatePopEvalAsm =\n  [ Get_global sp  -- bp = [sp + 4]\n  , I32_load 2 4\n  , Set_global bp\n  , Get_global sp  -- sp = sp + local_0\n  , Get_local 0  -- Should be 4*(n + 1).\n  , I32_add\n  , Set_global sp\n  , Get_global sp  -- [[sp + 4]] = Ind\n  , I32_load 2 4\n  , tag_const TagInd\n  , I32_store 2 0\n  , Get_global sp  -- [[sp + 4] + 4] = bp\n  , I32_load 2 4\n  , Get_global bp\n  , I32_store 2 4\n  , Custom $ CallSym \"#eval\"\n  , End\n  ]\nallocAsm :: [QuasiWasm]\nallocAsm =\n  [ Loop Nada\n    [ Get_local 0  -- Break when local0 == 0\n    , I32_eqz\n    , Br_if 1\n    , Get_local 0  -- local0 = local0 - 1\n    , I32_const 1\n    , I32_sub\n    , Set_local 0\n    , Get_global hp  -- #push32 hp\n    , Custom $ CallSym \"#push32\"\n    , Get_global hp  -- [hp] = TagInd\n    , tag_const TagInd\n    , I32_store 2 0\n    , Get_global hp  -- hp = hp + 8\n    , I32_const 8\n    , I32_add\n    , Set_global hp\n    , Br 0\n    ]\n  , End\n  ]\nupdateIndAsm :: [WasmOp]\nupdateIndAsm =\n  [ Get_global sp  -- sp = sp + 4\n  , I32_const 4\n  , I32_add\n  , Set_global sp\n  -- local0 should be 4*(n + 1)\n  , Get_global sp  -- [[sp + local0] + 4] = [sp]\n  , Get_local 0\n  , I32_add\n  , I32_load 2 0\n  , Get_global sp\n  , I32_load 2 0\n  , I32_store 2 4\n  , End\n  ]\n\npairWith42Asm :: [WasmOp]\npairWith42Asm =  -- [sp + 4] = (local0, #RealWorld)\n  [ Get_global hp  -- [hp] = (TagSum | (2 << 8)).64\n  , I64_const $ fromIntegral $ fromEnum TagSum + 256 * 2\n  , I64_store 3 0\n  , Get_global hp  -- [hp + 8] = local0\n  , Get_local 0\n  , I32_store 2 8\n  , Get_global hp  -- [hp + 12] = 42\n  , I32_const 42\n  , I32_store 2 12\n  , Get_global sp  -- [sp + 4] = hp\n  , Get_global hp\n  , I32_store 2 4\n  , Get_global hp  -- hp = hp + 16\n  , I32_const 16\n  , I32_add\n  , Set_global hp\n  , End\n  ]\n-- | [sp + 4] = ((), #RealWorld)\n-- TODO: Optimize by placing this special value at a known location in memory.\nnil42Asm :: [QuasiWasm]\nnil42Asm =\n  [ Get_global hp  -- [hp].64 = TagSum\n  , I64_const $ fromIntegral $ fromEnum TagSum\n  , I64_store 3 0\n  , Get_global hp  -- PUSH hp\n  , Get_global hp  -- hp = hp + 8\n  , I32_const 8\n  , I32_add\n  , Set_global hp\n  , Custom $ CallSym \"#pairwith42\"\n  , End\n  ]\n\ntoWasmType :: Type -> WasmType\ntoWasmType (TC \"Int\") = I64\ntoWasmType _ = I32\n\naddHelper :: [Type] -> [[Ins]] -> State CompilerState ()\naddHelper ty ms = do\n  st <- get\n  put st { helpers = (show ty, f):helpers st }\n  where\n  f = case (ty, ms) of\n    ([t], [encoder]) ->\n      -- When sending a message with only one item, we have a bare argument\n      -- instead of an argument tuple\n      -- Evaluate single argument.\n      [ Push 1\n      , WasmPush encoder t\n      , Push 0  -- Slot.\n      , Eval\n      , WasmCallIndirect ty\n      ]\n    _ ->\n      -- Evaluate argument tuple.\n      [ Push 1\n      , Eval\n      , Split $ length ms\n      ] ++ zipWith WasmPush ms ty ++\n      [ Push 0  -- Slot.\n      , Eval\n      , WasmCallIndirect ty\n      ]\n"
  },
  {
    "path": "src/Ast.hs",
    "content": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE DeriveGeneric #-}\nmodule Ast\n  ( Ast(..)\n  , AAst(..)\n  , AstF(..)\n  , deAnn\n  , bifix\n  , ffix\n  , Type(..)\n  ) where\n\nimport Data.Binary (Binary)\n#ifndef __HASTE__\nimport Data.ByteString.Short (ShortByteString)\n#endif\nimport Data.Int\nimport GHC.Generics (Generic)\n\n#ifdef __HASTE__\ntype ShortByteString = String\n#endif\n\ninstance Binary Type\n\ninfixl 5 :@\ndata AstF a = Qual String String\n  | CallSlot [Type] [a]\n  | Pack Int Int | I Int64 | S ShortByteString | Var String\n  | a :@ a | Cas a [(a, a)]\n  | Lam [String] a | Let [(String, a)] a\n  | DictIndex Int | Placeholder String Type\n  deriving (Read, Show, Functor, Foldable, Traversable, Generic)\n\nnewtype Ast = Ast (AstF Ast) deriving (Show, Generic)\n\n-- Annotated AST.\ndata AAst a = AAst a (AstF (AAst a)) deriving (Show, Functor)\n\ndeAnn :: AAst a -> Ast\ndeAnn = ffix $ \\h (AAst _ ast) -> Ast $ h ast\n\nbifix :: (a -> b) -> (b -> a) -> a\nbifix g f = f $ g $ bifix g f\n\nffix :: Functor f => ((f a -> f b) -> a -> b) -> a -> b\nffix = bifix fmap\n\ninfixr 5 :->\ndata Type = TC String | TApp Type Type | Type :-> Type\n  | TV String | GV String deriving (Read, Show, Eq, Generic)\n"
  },
  {
    "path": "src/Boost.hs",
    "content": "{-# LANGUAGE CPP #-}\nmodule Boost\n  ( QuasiWasm\n  , QuasiWasmHelper(..)\n  , tag_const, Tag(..)\n  , Boost(..)\n#ifdef __HASTE__\n  , (<>)\n#endif\n  ) where\n\n#ifndef __HASTE__\nimport Data.Semigroup ()\n#endif\n\nimport Ast\nimport WasmOp\n\n-- | Data on the heap is 64-bit aligned. The first 8 bits hold a tag.\n--\n-- The following tables describe the field at a given offset of an object\n-- on the heap. All fields are 32 bits wide except the value field of a 64-bit\n-- integer type.\n--\n-- Int64s:\n--    0 TagInt\n--    8 64-bit value\n--\n-- Ports:\n--    0 TagRef\n--    4 32-bit value\n--\n-- Coproduct (sum) types:\n--    0 TagSum | (arity << 8)\n--    4 Enum\n--    8, 12.. Heap addresses of components.\n--\n-- Application `f x`:\n--    0 TagAp\n--    4 Unused\n--    8 f\n--   12 x\n--\n-- Global function:\n--    0 TagGlobal | (arity << 8)\n--    4 Function index\n--\n-- Indirection:\n--    0 TagInd\n--    4 Heap address of target\n--\n-- String:\n--    0 TagString\n--    4 address\n--    8 offset\n--    12 length\n--\n-- For example, `Just 42` is represented by:\n--\n--   [TagSum, 1, p], where p points to [TagInt, 0, 42]\n--\n-- where each list item is a 32-bit integer.\n\ndata Tag = TagAp | TagInd | TagGlobal | TagInt | TagRef | TagSum | TagString deriving Enum\n\ntag_const :: Tag -> CustomWasmOp a\ntag_const = I32_const . fromIntegral . fromEnum\n\n-- | A few helpers for inline assembly.\ntype QuasiWasm = CustomWasmOp QuasiWasmHelper\ndata QuasiWasmHelper =\n    CallSym String  -- Find function index and call it.\n  | ReduceArgs Int  -- Copy arguments from heap and reduce them to WHNF.\n  deriving Show\n\ntype WasmImport = ((String, String), ([WasmType], [WasmType]))\n\n-- | A Boost is a custom collection of extra declarations and functions that\n-- are added to a binary.\ndata Boost = Boost\n  -- Wasm import declarations.\n  { boostImports :: [WasmImport]\n  -- Haskell definitions.\n  , boostPrelude :: String\n  -- Primitive Haskell functions.\n  , boostPrims :: [(String, (Type, [QuasiWasm]))]\n  -- Internal wasm functions, indexed by strings for CallSym.\n  , boostWasm :: [(String, (([WasmType], [WasmType]), [QuasiWasm]))]\n  }\n\n#ifdef __HASTE__\n(<>) :: Boost -> Boost -> Boost\nBoost a b c d <> Boost x y z w = Boost (a ++ x) (b ++ y) (c ++ z) (d ++ w)\n#else\ninstance Semigroup Boost where\n  Boost a b c d <> Boost x y z w = Boost (a <> x) (b <> y) (c <> z) (d <> w)\n\ninstance Monoid Boost where\n  mempty = Boost [] [] [] []\n  mappend = (<>)\n#endif\n"
  },
  {
    "path": "src/DHC.hs",
    "content": "{-# LANGUAGE CPP #-}\n#ifdef __HASTE__\n{-# LANGUAGE PackageImports #-}\n#endif\nmodule DHC\n  ( AstF(..), Ast(..), Clay(..), Type(..)\n  , parseDefs\n  , arityFromType, hsToAst, liftLambdas\n  ) where\nimport Control.Arrow\nimport Control.Monad\n#ifdef __HASTE__\nimport \"mtl\" Control.Monad.State\n#else\nimport Control.Monad.Reader\nimport Control.Monad.State\n#endif\nimport Data.Char\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport Data.Maybe\nimport Data.Traversable\n\nimport Ast\nimport Boost\nimport Parse\n\ntype QualType = (Type, [(String, String)])\ndata Clay = Clay\n  -- Public and secret functions are accompanied by a list of their\n  -- arguments types and a program for decoding them from the heap.\n  { publics :: [(String, [(Type, Ast)])]\n  , secrets :: [(String, [(Type, Ast)])]\n  , stores :: [(String, Type)]\n  , funTypes :: Map String QualType\n  , supers :: Map String Ast\n  , genDecls :: [(String, Type)]\n  , datas :: Map String (Maybe (Int, Int), Type)\n  -- | e.g. \"==\" -> (type \"a -> a -> Bool\", 0, (\"Eq\", \"a\"))\n  -- The number is the method's index in the sorted list of methods.\n  , methods :: Map String (Type, Int, (String, String))\n  -- | e.g. \"Monad\" -> [\">>=\", \"pure\"]. List is sorted.\n  , classes :: Map String [String]\n  -- We delay processing instance declarations until after all class\n  -- definitions have been handled, including those from the prelude.\n  , preInstances :: [([(String, String)], String, Type, [(String, Ast)])]\n  -- | e.g. \"Monad\" ->\n  --   [ (TC \"Maybe\", Ast of tuple (maybe->>=, maybe-pure))\n  --   , (TC \"IO\", Ast of tuple (io->>=, io-pure))\n  --   ]\n  , instances :: Map String [(QualType, Ast)]\n  , recursiveCompile :: String -> String\n  }\n\nnewClay :: (String -> String) -> [TopLevel] -> Either String Clay\nnewClay rCompile ts = do\n  p0 <- foldM f emptyClay ts\n  let missing = (fst <$> publics p0) \\\\ M.keys (supers p0)\n  unless (null missing) $ Left $ \"missing public functions: \" ++ show missing\n  let\n    storeCons s\n      | Just ty <- lookup s $ genDecls p0 = (s, ty)\n      | otherwise = (s, TC \"Store\" `TApp` TV ('@':s))\n  pure $ p0 { stores = storeCons . fst <$> stores p0 }\n  where\n  emptyClay = Clay [] [] [] M.empty M.empty [] M.empty M.empty M.empty [] M.empty rCompile\n  f p t = case t of\n    Super (name, ast) -> Right p { supers = M.insert name ast $ supers p }\n    ClassDecl s ty unsorted -> Right p\n      { methods = m1\n      , classes = M.insert s (fst <$> xs) $ classes p\n      }\n      where\n      xs = sortOn fst unsorted\n      m1 = foldl' addMethod (methods p) $ zip [0..] xs\n      addMethod m (idx, (mName, mType)) = M.insert mName (mType, idx, (s, ty)) m\n    InstanceDecl ctx cl ty is -> Right p\n      { preInstances = (ctx, cl, ty, sortOn fst is):preInstances p }\n    GenDecl x -> Right p { genDecls = x:genDecls p }\n    DataDecl xs -> Right p { datas = foldl' (\\m (k, v) -> M.insert k v m) (datas p) xs }\n    PublicDecl xs -> Right p { publics = zip xs $ repeat [] }\n    StoreDecl xs -> Right p { stores = zip xs $ repeat undefined }\n\n-- | Adds a dictionary object for a given instance, along with supercombinators\n-- for each of the method implementations.\n--\n-- A dictionary is a tuple of `Var` nodes that refer to this instance's\n-- implementation of the methods, ordered lexicographically.\n-- Must be run after processing class declarations.\n--\n-- If there is only one method in the typeclass, then instead of a tuple of\n-- size 1, we generate a single Var node.\n--\n-- For example, the Maybe Monad instance results in the tuple:\n--\n--   (Var \"Maybe->>=\", Var \"Maybe-pure\")\n--\n-- along with the supercombinators:\n--\n--   (Maybe->>=) x f = case x of { Nothing -> Nothing; Just a -> f a }\n--   (Maybe-pure) x = Just x\"\n--\n-- Actually, the generated prefixes are uglier because we just use `show`,\n-- which produces \"TC \\\"Maybe\\\"\" instead of \"Maybe\".\nmkDict :: Clay -> ([(String, String)], String, Type, [(String, Ast)]) -> Either String Clay\nmkDict p (ctx, cls, ty, is) = case M.lookup cls $ classes p of\n  Nothing -> Left $ \"unknown typeclass: \" ++ cls\n  Just ms -> do\n    when (sorted /= ms) $ Left $ \"instance methods disagree with class: \" ++ cls ++ \" \" ++ show ty\n    Right p\n      { instances = M.insertWith (++) cls [((ty, ctx), dict)] $ instances p\n      , supers = supers p `M.union` M.fromList (first (methodPrefix ty) <$> is)\n      }\n    where\n    dict | [one] <- sorted = Ast $ Var $ methodPrefix ty one\n         | otherwise = foldl' ((Ast .) . (:@)) (Ast $ Pack 0 $ length is) $ Ast . Var . methodPrefix ty <$> sorted\n    sorted = sort $ fst <$> is\n\nmethodPrefix :: Type -> String -> String\nmethodPrefix ty method = concat [show ty, \"-\", method]\n\nhsToAst :: Boost -> QQuoter -> String -> Either String Clay\nhsToAst boost qq prog = do\n  cl0 <- showErr $ newClay (either error id . qq \"wasm\") =<< either (Left . show) Right (parseDfnHs qq prog)\n  preludeDefs <- parseDefs $ boostPrelude boost\n  let\n    cl1 = extractSecrets cl0\n      { supers = supers preludeDefs `M.union` supers cl0\n      , datas = datas preludeDefs `M.union` datas cl0\n      , methods = methods preludeDefs `M.union` methods cl0\n      , classes = classes preludeDefs `M.union` classes cl0\n      , preInstances = preInstances preludeDefs ++ preInstances cl0\n      }\n  cl <- foldM mkDict cl1 $ preInstances cl1\n  (inferred, storageCons) <- inferType boost cl\n  let\n    -- TODO: Handle non-strict case expressions.\n    subbedDefs =\n        (second expandCase <$>)\n      . liftLambdas\n      -- Saturating constructors may create lambdas, so must occur before\n      -- we lift lambdas.\n      . (second saturateCons <$>)\n      . (second snd <$>) $ inferred\n    types = M.fromList $ second fst <$> inferred\n    stripStore (TApp (TC \"Store\") t) = t\n    stripStore _ = error \"expect Store\"\n    addDecoders :: String -> (String, [(Type, Ast)])\n    addDecoders s = (s, addDec [] ty)\n      where\n      Just (ty, _) = M.lookup s types\n      addDec acc t = case t of\n        a :-> b -> addDec ((a, dictSolve inferred cl [] M.empty $ Ast (Placeholder \"dfromUnboxed\" a)) : acc) b\n        TApp (TC \"IO\") (TC \"()\") -> reverse acc\n        _ -> error \"exported functions must return IO ()\"\n  pure cl\n    { publics = addDecoders . fst <$> publics cl\n    , secrets = addDecoders . fst <$> secrets cl\n    , supers = M.fromList subbedDefs\n    , funTypes = types\n    , stores = second (stripStore . typeSolve storageCons) <$> stores cl }\n  where\n  showErr = either (Left . show) Right\n\njustHere :: QQuoter\njustHere \"here\" s = Right s\njustHere _ _ = Left \"bad scheme\"\n\nparseDefs :: String -> Either String Clay\nparseDefs s = newClay undefined =<< either (Left . show) Right (parseDfnHs justHere s)\n\n-- The Constraints monad combines a State monad and an Either monad.\n-- The state consists of the set of constraints and next integer available\n-- for naming a free variable, and the contexts of each variable.\ndata ConState = ConState\n  String -- Prefix for generated free variables.\n  Int  -- Integer for next free variable name.\n  [(Type, Type)]  -- Constraints added so far.\n  (Map String [String])  -- Contexts of each variable.\nnewtype Constraints a = Constraints (ConState -> Either String (a, ConState))\n\nbuildConstraints :: String -> Constraints a -> Either String (a, ConState)\nbuildConstraints pre (Constraints f) = f $ ConState pre 0 [] M.empty\n\ninstance Functor Constraints where fmap = liftM\ninstance Applicative Constraints where { (<*>) = ap ; pure = return }\ninstance Monad Constraints where\n  Constraints c1 >>= fc2 = Constraints $ \\cs -> case c1 cs of\n    Left err -> Left err\n    Right (r, cs2) -> let Constraints c2 = fc2 r in c2 cs2\n  return a = Constraints $ \\p -> Right (a, p)\n\nnewTV :: Constraints Type\nnewTV = Constraints $ \\(ConState pre i cs m) -> Right (TV $ pre ++ show i, ConState pre (i + 1) cs m)\n\naddConstraint :: (Type, Type) -> Constraints ()\naddConstraint c = Constraints $ \\(ConState pre i cs m) -> Right ((), ConState pre i (c:cs) m)\n\naddContext :: String -> String -> Constraints ()\naddContext s x = Constraints $ \\(ConState pre i cs m) -> Right ((), ConState pre i cs $ M.insertWith union x [s] m)\n\ntype Globals = Map String (Maybe (Int, Int), Type)\n\n-- | Gathers constraints.\n-- Replaces overloaded methods with Placeholder.\n-- Replaces data constructors with Pack.\n-- For DFINITY, replaces `my.f` with `#preslot n` where n is the slot number\n-- preloaded with the secret or public function `f`.\ngather\n  :: Clay\n  -> Globals\n  -> [(String, QualType)]\n  -> Ast\n  -> Constraints (AAst Type)\ngather cl globs env (Ast ast) = case ast of\n  I i -> pure $ AAst (TC \"Int\") $ I i\n  S s -> pure $ AAst (TC \"String\") $ S s\n  Pack m n -> do  -- Only tuples are pre`Pack`ed.\n    xs <- replicateM n newTV\n    let r = foldr1 TApp $ TC \"()\":xs\n    pure $ AAst (foldr (:->) r xs) $ Pack m n\n  Qual \"my\" f\n    | Just n <- elemIndex f (fst <$> publics cl ++ secrets cl) -> rec env $ Ast (Ast (Var \"#preslot\") :@ Ast (I $ fromIntegral n))\n    | otherwise -> bad $ \"must be secret or public: \" ++ f\n  Var \"_\" -> do\n    x <- newTV\n    pure $ AAst x $ Var \"_\"\n  Var v\n    | Just qt <- lookup v env -> do\n      (t1, qs1) <- instantiate qt\n      pure $ foldl' ((AAst t1 .) . (:@)) (AAst t1 $ Var v) $ (\\(a, b) -> AAst (TC $ \"Dict-\" ++ a) $ Placeholder a (TV b)) <$> qs1\n    | Just (ty, _, typeClass) <- M.lookup v $ methods cl -> do\n      ~(t1, [(_, x)]) <- instantiate (ty, [typeClass])\n      pure $ AAst t1 $ Placeholder v $ TV x\n    | Just (ma, gt) <- M.lookup v globs ->\n      flip AAst (maybe (Var v) (uncurry Pack) ma) . fst <$> instantiate (gt, [])\n    | otherwise -> bad $ \"undefined: \" ++ v\n  t :@ u -> do\n    a@(AAst tt _) <- rec env t\n    b@(AAst uu _) <- rec env u\n    x <- newTV\n    addConstraint (tt, uu :-> x)\n    pure $ AAst x $ a :@ b\n  Lam args u -> do\n    ts <- mapM (const newTV) args\n    a@(AAst tu _) <- rec (zip (filter (/= \"_\") args) (zip ts $ repeat []) ++ env) u\n    pure $ AAst (foldr (:->) tu ts) $ Lam args a\n  Cas e as -> do\n    aste@(AAst te _) <- rec env e\n    x <- newTV\n    astas <- forM as $ \\(p, a) -> do\n      let\n        varsOf (Ast (t :@ u)) = varsOf t ++ varsOf u\n        varsOf (Ast (Var v)) | isLower (head v) = [v]\n        varsOf _ = []\n      when (varsOf p /= nub (varsOf p)) $ bad \"multiple binding in pattern\"\n      envp <- forM (varsOf p) $ \\s -> (,) s . flip (,) [] <$> newTV\n      -- TODO: Check p is a pattern.\n      astp@(AAst tp _) <- rec (envp ++ env) p\n      addConstraint (te, tp)\n      asta@(AAst ta _) <- rec (envp ++ env) a\n      addConstraint (x, ta)\n      pure (astp, asta)\n    pure $ AAst x $ Cas aste astas\n  Let ds body -> do\n    es <- forM (fst <$> ds) $ \\s -> (,) s <$> newTV\n    let envLet = (second (flip (,) []) <$> es) ++ env\n    ts <- forM (snd <$> ds) $ rec envLet\n    mapM_ addConstraint $ zip (snd <$> es) (afst <$> ts)\n    body1@(AAst t _) <- rec envLet body\n    pure $ AAst t $ Let (zip (fst <$> ds) ts) body1\n  _ -> fail $ \"BUG! unhandled: \" ++ show ast\n  where\n    rec = gather cl globs\n    bad = Constraints . const . Left\n    afst (AAst t _) = t\n\n-- | Instantiate generalized variables.\n-- Returns type where all generalized variables have been instantiated along\n-- with the list of type constraints where each generalized variable has\n-- been instantiated with the same generated names.\ninstantiate :: QualType -> Constraints (Type, [(String, String)])\ninstantiate (ty, qs) = do\n  (gvmap, result) <- f [] $ subStore ty\n  let qInstances = second (getVar gvmap) <$> qs\n  forM_ qInstances $ uncurry addContext\n  pure (result, qInstances)\n  where\n  getVar m v = x where Just (TV x) = lookup v m\n  f m (GV s) | Just t <- lookup s m = pure (m, t)\n             | otherwise = do\n               x <- newTV\n               pure ((s, x):m, x)\n  f m (t :-> u) = do\n    (m1, t') <- f m t\n    (m2, u') <- f m1 u\n    pure (m2, t' :-> u')\n  f m (t `TApp` u) = do\n    (m1, t') <- f m t\n    (m2, u') <- f m1 u\n    pure (m2, t' `TApp` u')\n  f m t = pure (m, t)\n\n-- Change \"Store a\" -> \"(AnyDfn -> IO (), IO AnyDfn)\".\nsubStore :: Type -> Type\nsubStore ty = case ty of\n  t :-> u -> subStore t :-> subStore u\n  TC \"Store\" `TApp` u -> TApp (TC \"()\") $\n    (unboxed (subStore u) :-> io (TC \"()\")) `TApp` io (unboxed $ subStore u)\n  t `TApp` u -> subStore t `TApp` subStore u\n  _ -> ty\n  where\n  io = TApp $ TC \"IO\"\n  unboxed = TApp $ TC \"Unboxed\"\n\ngeneralize\n  :: [(String, (QualType, Ast))]\n  -> Clay\n  -> Solution\n  -> (String, AAst Type)\n  -> (String, (QualType, Ast))\ngeneralize scs cl (soln, ctx) (fun, a0@(AAst t0 _)) = (fun, (qt, a1)) where\n  qt@(_, qs) = runState (generalize' ctx $ typeSolve soln t0) []\n  -- TODO: Compute nub of qs?\n  dsoln = zip qs $ (\"#d\" ++) . show <$> [(0::Int)..]\n  -- TODO: May be useful to preserve type annotations?\n  a1 = dictSolve scs cl dsoln soln ast\n  dvars = snd <$> dsoln\n  ast = case deAnn a0 of\n    Ast (Lam ss body) -> Ast $ Lam (dvars ++ ss) $ expandFun body\n    body -> Ast $ Lam dvars $ expandFun body\n  -- TODO: Take shadowing into account.\n  expandFun\n    | null dvars = id\n    | otherwise  = ffix $ \\h (Ast a) -> Ast $ case a of\n      Var v | v == fun -> foldl' (\\x d -> (Ast x :@ Ast (Var d))) a dvars\n      _ -> h a\n\n-- Replaces e.g. `TV x` with `GV x` and adds its constraints\n-- (e.g. Eq x, Monad x) to the common pool.\ngeneralize' :: Map String [String] -> Type -> State [(String, String)] Type\ngeneralize' ctx ty = case ty of\n  TV s -> do\n    case M.lookup s ctx of\n      Just cs -> modify' $ union $ flip (,) s <$> cs\n      Nothing -> pure ()\n    pure $ GV s\n  u :-> v  -> (:->) <$> generalize' ctx u <*> generalize' ctx v\n  TApp u v -> TApp  <$> generalize' ctx u <*> generalize' ctx v\n  _        -> pure ty\n\ndictSolve\n  :: [(String, (QualType, Ast))]\n  -> Clay\n  -> [((String, String), String)]\n  -> Map String Type\n  -> Ast\n  -> Ast\ndictSolve scs cl dsoln soln = ffix $ \\h (Ast ast) -> case ast of\n  -- Replace method Placeholders with selector and dictionary Placeholder.\n  Placeholder s t | Just (_, idx, (typeClass, _)) <- M.lookup s $ methods cl ->\n    case length $ classes cl M.! typeClass of\n      1 -> rec (Ast $ Placeholder typeClass $ typeSolve soln t)\n      _ -> Ast (DictIndex idx) @@ rec (Ast $ Placeholder typeClass $ typeSolve soln t)\n  -- Replace dictionary Placeholders.\n  Placeholder d t -> case typeSolve soln t of\n    TV v -> Ast $ Var $ fromMaybe (error $ \"unsolvable: \" ++ show (d, v)) $ lookup (d, v) dsoln\n    u -> findInstance d u\n  _       -> Ast $ h ast\n  where\n  aVar = Ast . Var\n  infixl 5 @@\n  x @@ y = Ast $ x :@ y\n  rec = dictSolve scs cl dsoln soln\n  findInstance typeClass t | Just insts <- M.lookup typeClass $ instances cl\n    = case matchInstance typeClass t insts of\n      Nothing -> error \"BUG! missing instance\"\n      Just ast -> rec ast\n  findInstance \"Message\" t = Ast . CallSlot tu $ rec . Ast . Placeholder \"ctoUnboxed\" <$> tu\n    where tu = either (error . show) id $ listFromTupleType t\n  -- The \"Storage\" typeclass has four methods:\n  --  1. toAnyRef\n  --  2. fromAnyRef\n  --  3. toUnboxed\n  --  4. fromUnboxed\n  -- For boxed types such as databufs, 1 and 2 are the same as 3 and 4.\n  -- For unboxed types, such as integers, 1 encodes to a databuf, 2 decodes\n  -- from a databuf, and 3 and 4 leave the input unchanged.\n  findInstance \"Storage\" t = case t of\n    TC \"Databuf\" -> boxy (aVar \"#reduce\") (aVar \"#reduce\")\n    TC \"String\" -> boxy (aVar \".\" @@ aVar \"#reduce\" @@ aVar \"toD\") (aVar \".\" @@ aVar \"#reduce\" @@ aVar \"fromD\")\n    TC \"Port\" -> boxy (aVar \"#reduce\") (aVar \"#reduce\")\n    TC \"Actor\" -> boxy (aVar \"#reduce\") (aVar \"#reduce\")\n    TC \"Module\" -> boxy (aVar \"#reduce\") (aVar \"#reduce\")\n    TC \"Int\" -> Ast (Pack 0 4) @@ aVar \"Int-toAny\" @@ aVar \"Int-fromAny\" @@ aVar \"#reduce\" @@ aVar \"#reduce\"\n    TC \"I32\" -> Ast (Pack 0 4) @@ aVar \"#reduce\" @@ aVar \"#reduce\" @@ aVar \"#reduce\" @@ aVar \"#reduce\"\n    TC \"Bool\" -> Ast (Pack 0 4) @@ aVar \"Bool-toAny\" @@ aVar \"Bool-fromAny\" @@ aVar \"Bool-toUnboxed\" @@ aVar \"Bool-fromUnboxed\"\n    TApp (TC \"[]\") a -> let\n      ltai = aVar \"list_to_any_instance\" @@ rec (Ast $ Placeholder \"Storage\" a)\n      lfai = aVar \"list_from_any_instance\" @@ rec (Ast $ Placeholder \"Storage\" a)\n      in boxy ltai lfai\n    TC \"()\" -> boxy (aVar \"unit_to_any_instance\") (aVar \"unit_from_any_instance\")\n    TApp (TC \"()\") (TApp a b) -> let\n      -- TODO: Brittle. Relies on order constraints are found.\n      -- Implement contexts for instance declarations.\n      ptai = aVar \"pair_to_any_instance\" @@ rec (Ast $ Placeholder \"Storage\" b) @@ rec (Ast $ Placeholder \"Storage\" a)\n      pfai = aVar \"pair_from_any_instance\" @@ rec (Ast $ Placeholder \"Storage\" b) @@ rec (Ast $ Placeholder \"Storage\" a)\n      in boxy ptai pfai\n    e -> error $ \"BUG! no Storage for \" ++ show e\n    where boxy to from = Ast (Pack 0 4) @@ to @@ from @@ to @@ from\n  findInstance d t = error $ \"BUG! bad class: \" ++ show (d, t)\n\n  matchInstance typeClass t candidates = do\n    ((sol, ctx), (qt, ast)) <- lookupType cl t candidates\n    let\n      Just classMethods = M.lookup typeClass $ classes cl\n      mAsts = mkDictEntry <$> classMethods\n      -- TODO: Respect the order of the clauses in the context of `qt`.\n      mkDictEntry moo = foldl' addDict (Ast $ Var $ methodPrefix (fst qt) moo) $ M.assocs ctx\n      addDict a (zzz, [xxx]) = case typeSolve sol (TV zzz) of\n        TV v -> let Just dv = lookup (xxx, v) dsoln\n          in Ast $ a :@ Ast (Var dv)\n        tt -> Ast $ a :@ Ast (Placeholder xxx tt)\n      addDict _ _ = error \"TODO: more than one constraint per type variable\"\n    case () of\n      () | M.null sol -> Just ast\n         | [mAst] <- mAsts -> Just mAst\n         | otherwise -> Just $ foldl' ((Ast .) . (:@)) (Ast $ Pack 0 $ length classMethods) mAsts\n\ntypeSolve :: Map String Type -> Type -> Type\ntypeSolve soln t = case t of\n  TApp a b      -> rec a `TApp` rec b\n  a :-> b       -> rec a :-> rec b\n  TV x          -> fromMaybe t $ M.lookup x soln\n  _             -> t\n  where rec = typeSolve soln\n\nlookupType :: Clay -> Type -> [(QualType, Ast)] -> Maybe (Solution, (QualType, Ast))\nlookupType _ _ [] = Nothing\nlookupType cl t ((qt, ast):rest) = case unify cl cs m of\n  Left _ -> lookupType cl t rest\n  Right zzz -> Just (zzz, (qt, ast))\n  where\n  Right (_, ConState _ _ cs m) = buildConstraints \"#\" $ do\n    (ty, _) <- instantiate qt\n    addConstraint (ty, t)\n    pure ()\n\n-- | The `propagateClasses` and `propagateClassTyCon` functions of\n-- \"Implementing type classes\".\npropagate :: Clay -> [String] -> Type -> Either String [(String, [String])]\npropagate _ [] _ = Right []\npropagate _ cs (TV y) = Right [(y, cs)]\npropagate cl cs t = concat <$> mapM propagateTyCon cs where\n  propagateTyCon s | Just insts <- M.lookup s $ instances cl = case lookupType cl t insts of\n    Nothing -> Left $ unwords [\"no\", s, \"instance:\", show t]\n    -- For example, given `Eq [a]`, returns `Eq a`.\n    Just ((_, ctx), _) -> Right $ M.assocs ctx\n  propagateTyCon \"Storage\" = case t of\n    TApp (TC \"()\") (TApp a b) -> (++) <$> rec [\"Storage\"] a <*> rec [\"Storage\"] b\n    TApp (TC \"[]\") a -> rec [\"Storage\"] a\n    TC s | elem s messageTypes -> Right []\n    _ -> Left $ \"no Storage instance: \" ++ show t\n  propagateTyCon \"Message\" =\n    concat <$> (mapM (rec [\"Storage\"]) =<< listFromTupleType t)\n  propagateTyCon c = error $ \"TODO: \" ++ c\n  rec = propagate cl\n\n-- | Returns list of types from a tuple.\n-- e.g. (String, Int) becomes [String, Int]\n-- This should be trivial, but we represent tuples in a weird way!\nlistFromTupleType :: Type -> Either String [Type]\nlistFromTupleType ty = case ty of\n  TC \"()\" -> Right []\n  TApp (TC \"()\") rest -> weirdList rest\n  _ -> Right [ty]\n  where\n  -- Tuples are represented oddly in our Type data structure.\n  weirdList tup = case tup of\n    TC _ -> Right [tup]\n    TV _ -> Right [tup]\n    TApp h@(TC _) rest -> (h:) <$> weirdList rest\n    TApp h@(TV _) rest -> (h:) <$> weirdList rest\n    _ -> Left $ \"want tuple: \" ++ show tup\n\n-- e.g. [TV 'a' -> TC \"Int\", ...], [TV 'b', [\"Eq\", \"Ord\"], ...]\ntype Solution = (Map String Type, Map String [String])\n\nunify :: Clay -> [(Type, Type)] -> Map String [String] -> Either String Solution\nunify cl constraints ctx = execStateT (uni cl constraints) (M.empty, ctx)\n\nrefine :: Clay -> [(Type, Type)] -> Solution -> Either String Solution\nrefine cl constraints = execStateT (uni cl constraints)\n\nuni :: Clay -> [(Type, Type)] -> StateT (Map String Type, Map String [String]) (Either String) ()\nuni _ [] = do\n  (tm, qm) <- get\n  as <- forM (M.keys tm) $ follow . TV\n  put (M.fromList $ zip (M.keys tm) as, qm)\nuni _ ((GV _, _):_) = lift $ Left \"BUG! generalized variable in constraint\"\nuni _ ((_, GV _):_) = lift $ Left \"BUG! generalized variable in constraint\"\nuni cl ((lhs, rhs):cs) = do\n  z <- (,) <$> follow lhs <*> follow rhs\n  case z of\n    (s, t) | s == t -> rec cs\n    (TV x, TV y) -> do\n      when (x /= y) $ do\n        (tm, qm) <- get\n        -- (Ideally should union by rank.)\n        put (M.insert x (TV y) tm, case M.lookup x qm of\n          Just q -> M.insert y q $ M.delete x qm\n          _ -> qm)\n      rec cs\n    (TV x, t) -> if x `elem` freeTV t\n      -- TODO: Test infinite type detection.\n      then lift . Left $ \"infinite: \" ++ x ++ \" = \" ++ show t\n      else do\n        -- The `instantiateTyvar` function of \"Implementing type classes\".\n        (_, qm) <- get\n        -- For example, Eq [a] propagates to Eq a, which we record.\n        either (lift . Left) addQuals $ propagate cl (fromMaybe [] $ M.lookup x qm) t\n        modify' $ first $ M.insert x t\n        rec cs\n    (s, t@(TV _)) -> rec $ (t, s):cs\n    (TApp s1 s2, TApp t1 t2) -> rec $ (s1, t1):(s2, t2):cs\n    (s1 :-> s2, t1 :-> t2) -> rec ((s1, t1):(s2, t2):cs)\n    (s, t) -> lift . Left $ \"mismatch: \" ++ show s ++ \" /= \" ++ show t\n  where\n  addQuals = modify' . second . M.unionWith union . M.fromList\n  rec = uni cl\n\n-- Galler-Fischer-esque Data.Map (path compression).\nfollow :: Type -> StateT (Map String Type, a) (Either String) Type\nfollow t = case t of\n  TApp a b -> TApp <$> follow a <*> follow b\n  a :-> b  -> (:->) <$> follow a <*> follow b\n  TV x     -> do\n    (tm, qm) <- get\n    case M.lookup x tm of\n      Just u -> do\n        z <- follow u\n        put (M.insert x z tm, qm)\n        pure z\n      Nothing -> pure $ TV x\n  _        -> pure t\nfreeTV :: Type -> [String]\nfreeTV t = case t of\n  TApp a b -> freeTV a ++ freeTV b\n  a :-> b  -> freeTV a ++ freeTV b\n  TV tv    -> [tv]\n  _        -> []\n\narityFromType :: Type -> Int\narityFromType = f 0 where\n  f acc (_ :-> r) = f (acc + 1) r\n  f acc _ = acc\n\nboostTypes :: Boost -> Map String (Maybe (Int, Int), Type)\nboostTypes b = M.fromList $ second ((,) Nothing . fst) <$> boostPrims b\n\n-- | Find functions used as funrefs but not declared public.\nextractSecrets :: Clay -> Clay\nextractSecrets cl = cl { secrets = zip (concatMap filterSecrets $ M.elems $ supers cl) $ repeat [] }\n  where\n  filterSecrets = bifix foldMapDefault $ \\h (Ast ast) -> case ast of\n    Qual \"my\" f -> if elem f $ fst <$> publics cl then [] else [f]\n    _ -> h ast\n\ninferType\n  :: Boost\n  -> Clay\n  -- Returns types of definitions and stores.\n  -> Either String ([(String, (QualType, Ast))], Map String Type)\ninferType boost cl = foldM inferMutual ([], M.empty) $ map (map (\\k -> (k, ds M.! k))) sortedDefs where\n  ds = supers cl\n  -- Groups of definitions, sorted in the order we should infer their types.\n  sortedDefs = reverse $ scc (callees cl ds) $ M.keys ds\n  -- List notation is a special case in Haskell.\n  -- This is \"data [a] = [] | a : [a]\" in spirit.\n  listPresets = M.fromList\n    [ (\"[]\", (Just (0, 0), TApp (TC \"[]\") a))\n    , (\":\",  (Just (1, 2), a :-> TApp (TC \"[]\") a :-> TApp (TC \"[]\") a))\n    ] where a = GV \"a\"\n  globs = listPresets\n    `M.union` datas cl\n    `M.union` boostTypes boost\n    `M.union` M.fromList (second ((,) Nothing) <$> stores cl)\n  inferMutual :: ([(String, (QualType, Ast))], Map String Type) -> [(String, Ast)] -> Either String ([(String, (QualType, Ast))], Map String Type)\n  inferMutual (acc, accStorage) grp = do\n    (typedAsts, ConState _ _ cs m) <- buildConstraints \"_\" $ forM grp $ \\(s, d) -> do\n      t <- gather cl globs env d\n      addConstraint (TV $ '*':s, annOf t)\n      when (s == \"main\") $ addConstraint (TV $ '*':s, TApp (TC \"IO\") $ TC \"()\")\n      case s `lookup` genDecls cl of\n        Nothing -> pure ()\n        Just gt -> do\n          (ty, _) <- instantiate (gt, [])\n          addConstraint (TV $ '*':s, ty)\n      pure (s, t)\n    initSol <- unify cl cs m\n    sol@(solt, _) <- foldM (checkPubSecs cl) initSol (fst <$> grp)\n    let storageCons = M.filterWithKey (\\k _ -> head k == '@') solt\n    -- TODO: Look for conflicting storage constraints.\n    pure ((++ acc) $ generalize acc cl sol <$> typedAsts, accStorage `M.union` storageCons)\n    where\n    annOf (AAst a _) = a\n    tvs = TV . ('*':) . fst <$> grp\n    env = zip (fst <$> grp) (zip tvs $ repeat []) ++ map (second fst) acc\n\ncheckPubSecs :: Clay -> Solution -> String -> Either String Solution\ncheckPubSecs cl (soln, ctx) s\n  | s /= \"main\" &&  -- Already handled.\n      (s `elem` (fst <$> publics cl ++ secrets cl)) =\n    -- Require `public` and `secret` functions to return IO ().\n    refine cl [(retType t, TApp (TC \"IO\") (TC \"()\"))] (soln, ctx)\n    -- TODO: Check no free variables are left, and\n    -- propagate [\"Storage\"] succeeds (returns []) for each argument type.\n  | otherwise = Right (soln, ctx)\n  where\n  Just t = M.lookup ('*':s) soln\n  retType (_ :-> a) = retType a\n  retType r = r\n\n-- TODO: For finding strongly-connected components, there's no need to find\n-- all dependencies. If a node has already been processed, we should avoid\n-- finding all its dependencies again. We can do this by passing in a list of\n-- nodes that have already been explored.\ncallees :: Clay -> Map String Ast -> String -> [String]\ncallees cl ds s = snd $ execState (go s) ([], []) where\n  go :: String -> State ([String], [String]) ()\n  go f = do\n    (env, acc) <- get\n    unless (elem f (env ++ acc) || M.member f (methods cl)) $ case M.lookup f ds of\n      -- TODO: If we knew the primitives (functions implemented in wasm, such\n      -- as `*`), then we could detect out-of-scope identifiers here.\n      Nothing -> pure ()  -- error $ \"not in scope: \" ++ f\n      Just d -> do\n        put (env, f:acc)\n        ast d\n  ast (Ast d) = case d of\n    x :@ y -> ast x >> ast y\n    Lam ss t -> do\n      env <- gets fst\n      modify $ first (ss ++)\n      ast t\n      modify $ first (const env)\n    Var v -> go v\n    Cas x as -> do\n      ast x\n      forM_ as $ \\(Ast p, e) -> do\n        env <- gets fst\n        modify $ first (caseVars p ++)\n        ast e\n        modify $ first (const env)\n    Let as x -> do\n      env <- gets fst\n      modify $ first ((fst <$> as) ++)\n      mapM_ ast $ snd <$> as\n      ast x\n      modify $ first (const env)\n    _ -> pure ()\n\n-- | Returns strongly connected components in topological order.\nscc :: Eq a => (a -> [a]) -> [a] -> [[a]]\nscc suc vs = foldl' (\\cs v -> assign cs [] v : cs) [] $ reverse $ topo suc vs where\n  assign cs c v | any (elem v) $ c:cs = c\n                | otherwise           = foldl' (assign cs) (v:c) (suc v)\n\ntopo :: Eq a => (a -> [a]) -> [a] -> [a]\ntopo suc vs = fst $ foldl' visit ([], []) vs where\n  visit (done, doing) v\n    | v `elem` done || v `elem` doing = (done, doing)\n    | otherwise = (\\(xs, x:ys) -> (x:xs, ys)) $\n      foldl' visit (done, v:doing) (suc v)\n\nfreeVars :: Ast -> AAst [String]\nfreeVars (Ast ast) = g [] ast where\n  g :: [String] -> AstF Ast -> AAst [String]\n  g cand (Lam ss (Ast a)) = AAst (vs \\\\ ss) $ Lam ss a1 where\n    a1@(AAst vs _) = g (union cand ss) a\n  g cand (Ast x :@ Ast y) = AAst (xv `union` yv) $ x1 :@ y1 where\n    x1@(AAst xv _) = g cand x\n    y1@(AAst yv _) = g cand y\n  g cand (Var v) | v `elem` cand = AAst [v] $ Var v\n                 | otherwise     = AAst []  $ Var v\n  g cand (Cas (Ast x) as) = AAst (foldl' union xv $ fst <$> as1) $ Cas x1 $ snd <$> as1 where\n    x1@(AAst xv _) = g cand x\n    as1 = map h as\n    h (Ast p, Ast e) = (vs1, (g [] p, e1)) where\n      e1@(AAst vs _) = g (cand `union` caseVars p) e\n      vs1 = vs \\\\ caseVars p\n  g cand (Let ds (Ast e)) = AAst (ev \\\\ binders) $ Let ds1 e1 where\n    e1@(AAst ev _) = g (cand `union` binders) e\n    binders = fst <$> ds\n    ds1 = map h ds\n    h (s, Ast x) = (s, g (cand `union` binders) x)\n  g _ x = ffix (\\h (Ast a) -> AAst [] $ h a) $ Ast x\n\ncaseVars :: AstF Ast -> [String]\ncaseVars (Var v) = [v]\ncaseVars (Ast x :@ Ast y) = caseVars x `union` caseVars y\ncaseVars _ = []\n\nsaturateCons :: Ast -> Ast\nsaturateCons = ffix $ \\h ast -> let\n  (t:spine) = spinal [] ast\n  in case t of\n    Pack m n | n > length spine -> Ast $ Lam vars body where\n      vars = show <$> [1..n - length spine]\n      aVars = Ast . Var <$> vars\n      body = foldl' ((Ast .) . (:@)) (Ast $ Pack m n) $ (++ aVars) $ getRs spine\n    _ -> foldl' ((Ast .) . (:@)) (Ast $ h t) $ getRs spine\n  where\n  spinal sp (Ast ast) = case ast of\n    (l :@ _) -> spinal (ast:sp) l\n    _ -> ast:sp\n  getRs = map (saturateCons . (\\(_ :@ r) -> r))\n\nliftLambdas :: [(String, Ast)] -> [(String, Ast)]\nliftLambdas scs = existingDefs ++ newDefs where\n  (existingDefs, (_, newDefs)) = runState (mapM f $ second freeVars <$> scs) ([], [])\n  f (s, AAst _ (Lam args body)) = do\n    modify $ first $ const [s]\n    body1 <- g body\n    pure (s, Ast $ Lam args body1)\n  f _ = error \"bad top-level definition\"\n  genName :: State ([String], [(String, Ast)]) String\n  genName = do\n    (names, ys) <- get\n    let\n      n = head $ filter (`notElem` names) $\n        (++ ('$':last names)) . show <$> [(0::Int)..]\n    put (n:names, ys)\n    pure n\n  g :: AAst [String] -> State ([String], [(String, Ast)]) Ast\n  g = bifix mapM $ \\h (AAst fvs ast) -> case ast of\n    Let ds t -> fmap Ast $ Let <$> mapM noLamb ds <*> g t where\n      noLamb (name, AAst dfvs (Lam ss body)) = do\n        n <- genName\n        body1 <- g body\n        modify $ second ((n, Ast $ Lam (dfvs ++ ss) body1):)\n        pure (name, foldl' ((Ast .) . (:@)) (Ast $ Var n) $ Ast . Var <$> dfvs)\n      noLamb (name, a) = (,) name <$> g a\n    lam@(Lam _ _) -> do\n      n <- genName\n      g $ AAst fvs $ Let [(n, AAst fvs lam)] (AAst [n] $ Var n)\n    _ -> Ast <$> h ast\n\nexpandCase :: Ast -> Ast\nexpandCase = ffix $ \\h (Ast ast) -> Ast $ case ast of\n  Cas e alts -> dupCase (rec e) alts\n  _ -> h ast\n  where\n    rec = expandCase\n    dupCase e [a] = Cas e $ evalState (expandAlt Nothing [] a) 0\n    dupCase e (a:as) = Cas e $ evalState (expandAlt (Just $ rec $ Ast $ Cas e as) [] a) 0\n    dupCase _ _ = error \"BUG! no case alternatives\"\n\n    -- TODO: Call `fromApList` only in last case alternative.\n    expandAlt :: Maybe Ast -> [(Ast, Ast)] -> (Ast, Ast) -> State Int [(Ast, Ast)]\n    expandAlt onFail deeper (p, a) = case fromApList p of\n      [Ast (Var _)] -> (:moreCases) . (,) p <$> g deeper a\n      [Ast (S s)] -> do\n        v <- genVar\n        a1 <- g deeper a\n        pure [(Ast $ Var v, Ast $ Cas (Ast (Ast (Ast (Var \"eq_String\") :@ Ast (Var v)) :@ Ast (S s))) $ (Ast $ Pack 1 0, a1):moreCases)]\n      [Ast (I n)] -> do\n        v <- genVar\n        a1 <- g deeper a\n        pure [(Ast $ Var v, Ast $ Cas (Ast (Ast (Ast (Var \"eq_Int\") :@ Ast (Var v)) :@ Ast (I n))) $ (Ast $ Pack 1 0, a1):maybe [] (pure . (,) (Ast $ Pack 0 0)) onFail)]\n      h@(Ast (Pack _ _)):xs -> (++ moreCases) <$> doPack [h] deeper xs a\n      _ -> error $ \"bad case: \" ++ show p\n\n      where\n      moreCases = maybe [] (pure . (,) (Ast $ Var \"_\")) onFail\n      doPack acc dpr [] body = (:moreCases) . (,) (foldl1 ((Ast .) . (:@)) acc) <$> g dpr body\n      doPack acc dpr (h:rest) body = do\n        gv <- Ast . Var <$> genVar\n        case h of\n          Ast (Var _) -> doPack (acc ++ [h]) dpr rest body\n          _ -> doPack (acc ++ [gv]) (dpr ++ [(gv, h)]) rest body\n      g [] body = pure body\n      g ((v, w):rest) body = fmap Ast $ Cas v <$> expandAlt onFail rest (w, body)\n\n    genVar = do\n      n <- get\n      put (n + 1)\n      pure $ \"c*\" ++ show n\n\n    fromApList :: Ast -> [Ast]\n    fromApList (Ast (a :@ b)) = fromApList a ++ [b]\n    fromApList a = [a]\n\nmessageTypes :: [String]\nmessageTypes = [\"Databuf\", \"String\", \"Actor\", \"Module\", \"Port\", \"I32\", \"Int\", \"Bool\", \"()\"]\n"
  },
  {
    "path": "src/Encode.hs",
    "content": "{-# LANGUAGE CPP #-}\nmodule Encode\n  ( encodeWasm\n  , ProtoWasm(..)\n  , leb128\n  , sleb128\n  , enc32\n  , encType\n  , WasmFun(..)\n  ) where\n\nimport Control.Arrow\n#ifdef __HASTE__\nimport qualified Data.Set as IS\nimport qualified Data.Map.Strict as IM\n#else\nimport Data.IntMap.Strict (restrictKeys)\nimport qualified Data.IntSet as IS\nimport qualified Data.IntMap.Strict as IM\n#endif\nimport Data.Bits\nimport Data.Char\nimport Data.List\nimport WasmOp\n\n#ifdef __HASTE__\ntype IntMap = IM.Map Int\ntype IntSet = IS.Set Int\nrestrictKeys :: IntMap a -> IntSet -> IntMap a\nrestrictKeys m s = IM.filterWithKey (\\k _ -> IS.member k s) m\n#endif\n\ntype FuncType = ([WasmType], [WasmType])\n\nwasmHeader :: [Int]\nwasmHeader = [0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]  -- Magic string, version.\n\nencWasmOp :: (FuncType -> Int) -> WasmOp -> [Int]\nencWasmOp findSig op = case op of\n  Get_local n -> 0x20 : leb128 n\n  Set_local n -> 0x21 : leb128 n\n  Tee_local n -> 0x22 : leb128 n\n  Get_global n -> 0x23 : leb128 n\n  Set_global n -> 0x24 : leb128 n\n  I64_const n -> 0x42 : sleb128 n\n  I32_const n -> 0x41 : sleb128 n\n  Call n -> 0x10 : leb128 n\n  Call_indirect sig -> 0x11 : leb128 (findSig sig) ++ [0]\n  I64_load m n -> [0x29, m, n]\n  I64_store m n -> [0x37, m, n]\n  I32_load m n -> [0x28, m, n]\n  I32_load8_u m n -> [0x2d, m, n]\n  I32_load16_u m n -> [0x2f, m, n]\n  I32_store m n -> [0x36, m, n]\n  I32_store8 m n -> [0x3a, m, n]\n  Br n -> 0xc : leb128 n\n  Br_if n -> 0xd : leb128 n\n  Br_table bs a -> 0xe : leb128 (length bs) ++ concatMap leb128 (bs ++ [a])\n  If t as [] -> [0x4, encType t] ++ concatMap rec as ++ [0xb]\n  If t as bs -> concat\n    [ [0x4, encType t]\n    , concatMap rec as\n    , [0x5]\n    , concatMap rec bs\n    , [0xb]\n    ]\n  Block t as -> [2, encType t] ++ concatMap rec as ++ [0xb]\n  Loop t as -> [3, encType t] ++ concatMap rec as ++ [0xb]\n  _ -> maybe (error $ \"unsupported: \" ++ show op) pure $ lookup op rZeroOps\n  where rec = encWasmOp findSig\n\nenc32 :: Int -> [Int]\nenc32 n = (`mod` 256) . div n . (256^) <$> [(0 :: Int)..3]\n\nencMartinType :: WasmType -> Int\nencMartinType t = case t of\n  Ref \"Actor\" -> 0x6f\n  Ref \"Module\" -> 0x6e\n  Ref \"Port\" -> 0x6d\n  Ref \"Databuf\" -> 0x6c\n  Ref \"Elem\" -> 0x6b\n  _ -> encType t\n\nencType :: WasmType -> Int\nencType t = case t of\n  I32 -> 0x7f\n  I64 -> 0x7e\n  F32 -> 0x7d\n  F64 -> 0x7c\n  AnyFunc -> 0x70\n  Nada -> 0x40\n  _ -> error $ \"bad type:\" ++ show t\n\nstandardSig :: FuncType -> FuncType\nstandardSig (a, b) = (standardType <$> a, standardType <$> b)\n\nstandardType :: WasmType -> WasmType\nstandardType t = case t of\n  Ref _ -> I32\n  _ -> t\n\nleb128 :: Int -> [Int]\nleb128 n | n < 128   = [n]\n         | otherwise = 128 + (n `mod` 128) : leb128 (n `div` 128)\n\nsleb128 :: (Bits a, Integral a) => a -> [Int]\nsleb128 n | n < 0     = fromIntegral <$> f (n .&. 127) (shiftR n 7)\n          | n < 64    = [fromIntegral n]\n          | n < 128   = [128 + fromIntegral n, 0]\n          | otherwise = 128 + (fromIntegral n `mod` 128) : sleb128 (n `div` 128)\n          where\n          f x (-1) | x < 64    = [x .|. 128, 127]\n                   | otherwise = [x]\n          f x y    = (x .|. 128):f (y .&. 127) (shiftR y 7)\n\nencCustom :: String -> [[Int]] -> [Int]\nencCustom s xs = 0 : lenc (encStr s ++ varlen xs ++ concat xs)\n\nencStr :: String -> [Int]\nencStr s = lenc $ ord <$> s\n\nvarlen :: [a] -> [Int]\nvarlen xs = leb128 $ length xs\n\nlenc :: [Int] -> [Int]\nlenc xs = varlen xs ++ xs\n\ndata ProtoWasm = ProtoWasm\n  { sectImports :: [((String, String), FuncType)]\n  , sectFunctions :: [WasmFun]\n  , tableSize :: Int\n  , sectGlobals :: [[Int]]\n  , sectExports :: [(String, Int)]\n  , sectElements :: [(Int, [Int])]\n  , sectPersist :: [(Int, WasmType)]\n  , sectDfn :: [(Int, [WasmType])]\n  , sectsCustom :: [(String, [[Int]])]\n  , sectsGeneric :: [(Int, [[Int]])]\n  }\n\nencodeWasm :: ProtoWasm -> [Int]\nencodeWasm fatP = concat\n  [ wasmHeader\n  -- Custom sections using Martin's annotations.\n  , encCustom \"types\" $ encMartinTypes . snd <$> sectDfn p\n  -- Martin subtracts the number of imports from the function index.\n  , encCustom \"typeMap\" $ zipWith (++) (leb128 . (+(-length (sectImports p))) . fst <$> sectDfn p) $ leb128 <$> [0..]\n  -- Encodes persistent globals.\n  , encCustom \"persist\" . fmap encMartinGlobal . sortOn fst $ sectPersist p\n  , encSect 1 $ encSig <$> sigs  -- Type section.\n  , encSect 2 $ importFun <$> sectImports p  -- Import section.\n  , encSect 3 $ pure . findSig . typeSig <$> sectFunctions p  -- Function section.\n  -- Table section.\n  -- Selects \"no-maximum\" (0).\n  , if tableSize p == 0 then [] else encSect 4 [[encType AnyFunc, 0] ++ leb128 (tableSize p)]\n  , concat $ getSect 5\n  , encSect 6 $ sectGlobals p  -- Global section.\n  , encSect 7 $  -- Export section.\n    -- The \"public\" functions.\n    [encStr s ++ (0 : leb128 n) | (s, n) <- sectExports p] ++\n    [ encStr \"memory\" ++ [2, 0]  -- 2 = external_kind Memory, 0 = memory index.\n    , encStr \"table\" ++ [1, 0]  -- 1 = external_kind Table, 0 = memory index.\n    ]\n  -- Export all globals. Forbidden by the spec, but our engine can handle it.\n#ifndef __HASTE__\n    ++ [ encStr (\"global\" ++ show n) ++ (3:leb128 n) | n <- [0..length (sectGlobals p) - 1]]\n#endif\n  , concat $ getSect 8\n  -- Element section.\n  , if null $ sectElements p then [] else\n    encSect 9 $ encTableChunk <$> sectElements p\n  , encSect 10 $ encProcedure <$> sectFunctions p\n  , concat $ getSect 11\n  , concatMap (uncurry encCustom) $ sectsCustom p\n  ]\n  where\n  p = trim fatP\n  encTableChunk (offset, entries) =\n    [ 0  -- Table 0 (only one in MVP).\n    , 0x41] ++ leb128 offset ++ [0xb]\n    ++ leb128 (length entries)\n    ++ concatMap leb128 entries\n  getSect k\n    | Just ns <- lookup k $ sectsGeneric p = [encSect k ns]\n    | otherwise = []\n  sigs = nub $ fmap standardSig $\n    (snd <$> sectImports p) ++  -- Types of imports.\n    (typeSig <$> sectFunctions p) ++  -- Types of functions.\n    concatMap (concatMap ciType . funBody) (sectFunctions p) -- Types of Call_indirect types.\n  ciType (Call_indirect t) = [t]\n  ciType (Block _ xs) = concatMap ciType xs\n  ciType (Loop _ xs) = concatMap ciType xs\n  ciType (If _ xs ys) = concatMap ciType $ xs ++ ys\n  ciType _ = []\n  encSig (ins, outs) = 0x60 : lenc (encType <$> ins) ++ lenc (encType <$> outs)\n  findSig :: FuncType -> Int\n  findSig sig\n    | Just n <- sigIndex = n\n    | otherwise = error $ \"BUG! missing sig in type section: \" ++ show sig\n    where sigIndex = elemIndex (standardSig sig) sigs\n  importFun ((m, f), ty) = encStr m ++ encStr f ++ [0, findSig ty]\n  encMartinTypes ts = 0x60 : lenc (encMartinType <$> ts) ++ [0]\n  encMartinGlobal (i, t) = [3] ++ leb128 i ++ leb128 (encMartinType t)\n  encProcedure wf = lenc $ leb128 (length $ localVars wf) ++\n    concatMap (\\t -> [1, encType $ standardType t]) (localVars wf) ++\n    concatMap (encWasmOp findSig) (funBody wf)\n  encSect t xs = t : lenc (varlen xs ++ concat xs)\n\n-- Trim unreachable wasm code.\ntrim :: ProtoWasm -> ProtoWasm\ntrim p = p\n  { sectImports = liveImps\n  , sectFunctions = IM.elems liveFuns\n  , sectExports = second (liveRenames IM.!) <$> sectExports p\n  , sectElements = filter (not . null . snd) $ second (map (liveRenames IM.!)) <$> sectElements p\n  , sectDfn = first (liveRenames IM.!) <$> sectDfn p\n  }\n  where\n  nonImports = IM.fromList $ zip [length $ sectImports p..] $ sectFunctions p\n  liveCalls = followCalls ((snd <$> sectExports p) `union` concatMap snd (sectElements p)) $ funBody <$> nonImports\n  liveRenames = IM.fromList $ zip (IS.elems liveCalls) [0..]\n  liveImps = map snd $ filter ((`IM.member` liveRenames) . fst) $ zip [0..] $ sectImports p\n  liveFuns = (\\wf -> wf { funBody = renumberCalls liveRenames $ funBody wf }) <$> restrictKeys nonImports (IM.keysSet liveRenames)\n"
  },
  {
    "path": "src/Hero/.gitignore",
    "content": ".DS_Store\n.stack-work*\n"
  },
  {
    "path": "src/Hero/Hero.hs",
    "content": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE NamedFieldPuns #-}\n\nmodule Hero.Hero\n  ( Wasm(dfnExports, haskell)\n  , CustomWasmOp(I32_const, I64_const), WasmOp\n  , Hero\n  , parseWasm\n  , invoke\n  , decode\n  , setSlot\n  , globals\n  , getMemory, putMemory\n  , getExport\n  , getSlot\n  , ripWasm\n  ) where\n\n#ifdef __HASTE__\nimport qualified Data.Map.Strict as IM\n#else\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\n#endif\nimport Data.Bits\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Word\n\nimport Hero.Parse\nimport WasmOp\n\n#ifdef __HASTE__\ntype IntMap = IM.Map Int\n#endif\n\ntype VMFun m a = [WasmOp] -> (a, Hero) -> m ([WasmOp], (a, Hero))\n-- | The import functions and table functions.\ntype VMEnv m a = ((String, String) -> VMFun m a, Int -> VMFun m a)\n\ndata Hero = Hero\n  { globs :: IntMap WasmOp\n  , locs  :: [IntMap WasmOp]\n  , stack :: [WasmOp]\n  , insts :: [[WasmOp]]\n  , mem   :: IntMap Word8\n  , sigs  :: IntMap ([WasmType], [WasmType])\n  , table :: IntMap (Either Int Int)\n  , wasm  :: Wasm\n  }\n\n-- | Reads global variables.\nglobals :: Hero -> [(Int, WasmOp)]\nglobals vm = IM.assocs $ globs vm\n\n-- | Reads a byte from memory.\ngetMemory :: Int32 -> Hero -> Word8\ngetMemory a vm = getWord8 a $ mem vm\n\n-- | Writes a byte to memory.\nputMemory :: Int32 -> Word8 -> Hero -> Hero\nputMemory a n vm = vm { mem = putWord8 a n $ mem vm }\n\ngetWord8 :: Int32 -> IntMap Word8 -> Word8\ngetWord8 a mem = fromMaybe 0 $ IM.lookup (fromIntegral a) mem\n\nputWord8 :: Int32 -> Word8 -> IntMap Word8 -> IntMap Word8\nputWord8 a n mem = IM.insert (fromIntegral a) n mem\n\ngetNum :: Integral n => Int -> Int32 -> IntMap Word8 -> n\ngetNum w addr mem = sum $ zipWith (*) bs ((256^) <$> [(0 :: Int)..]) where\n  bs = fromIntegral . (`getWord8` mem) . (addr +) <$> [0..fromIntegral w-1]\n\nputNum :: Integral n => Int -> Int32 -> n -> IntMap Word8 -> IntMap Word8\nputNum w addr n mem = foldl' f mem [0..w-1] where\n  f m k = putWord8 (addr + fromIntegral k) (getByte k) m\n  getByte k = fromIntegral $ ((fromIntegral n :: Word64) `shiftR` (8*k)) .&. 255\n\nrotateL32 :: Word32 -> Word32 -> Word32\nrotateL32 a b = rotateL a $ fromIntegral (b `mod` 32)\n\nrotateR32 :: Word32 -> Word32 -> Word32\nrotateR32 a b = rotateR a $ fromIntegral (b `mod` 32)\n\nshiftL32 :: Word32 -> Word32 -> Word32\nshiftL32 a b = shiftL a $ fromIntegral (b `mod` 32)\n\nshiftR32U :: Word32 -> Word32 -> Word32\nshiftR32U a b = shiftR a $ fromIntegral (b `mod` 32)\n\nshiftR32S :: Int32 -> Int32 -> Int32\nshiftR32S a b = shiftR a $ fromIntegral (b `mod` 32)\n\nshiftR64U :: Int64 -> Int64 -> Int64\nshiftR64U a b = fromIntegral $ shiftR ((fromIntegral a) :: Word64) $ fromIntegral ((fromIntegral b :: Word64) `mod` 64)\n\nshiftR64S :: Int64 -> Int64 -> Int64\nshiftR64S a b = fromIntegral $ shiftR ((fromIntegral a) :: Int64) $ fromIntegral ((fromIntegral b :: Int64) `mod` 64)\n\nshiftL64 :: Int64 -> Int64 -> Int64\nshiftL64 a b = shiftL a $ fromIntegral ((fromIntegral b :: Word64) `mod` 64)\n\nrotateR64 :: Int64 -> Int64 -> Int64\nrotateR64 a b = rotateR a $ fromIntegral ((fromIntegral b :: Word64) `mod` 64)\n\ndrop' :: Int -> [a] -> [a]\ndrop' n as | n > length as = error \"BAD DROP\"\n           | otherwise = drop n as\n\ntake' :: Int -> [a] -> [a]\ntake' n as | n > length as = error \"BAD TAKE\"\n           | otherwise = take n as\n\ninitLocal :: WasmType -> WasmOp\ninitLocal I32 = I32_const 0\ninitLocal I64 = I64_const 0\ninitLocal _ = error \"TODO\"\n\nrunImps :: Monad m => VMEnv m a -> (a, Hero) -> m ([WasmOp], (a, Hero))\nrunImps (imps, tabs) (st0, engine) = run st0 engine where\n  run st vm@Hero {insts, stack}\n    | null insts = pure (stack, (st, vm))\n    | null $ head insts = case tail insts of\n      ((Loop _ _:rest):t) -> run st vm {insts = rest:t}\n      _                   -> run st vm {insts = tail insts}\n  run st vm@Hero{globs, locs, stack, insts, mem} = case head $ head insts of\n    Call_indirect (inSig, _) -> do\n      let\n        -- TODO: Dynamic type-check.\n        inCount = length inSig\n        (I32_const i:params) = take' (inCount + 1) stack\n      (results, (a, vm1)) <- case table vm IM.! fromIntegral i of\n        Left n -> run st vm { insts = (Call n:head insts):tail insts }\n        Right n -> tabs n (reverse params) (st, step $ drop' (inCount + 1) stack)\n      run a $ setArgsVM results vm1\n    Call i -> let\n      Wasm {imports, functions} = wasm vm\n      fCount = length imports\n      in if i < fCount then do\n        let\n          (importName, (ins, _)) = imports!!i\n          k = length ins\n        (results, (a, vm1)) <- imps importName (reverse $ take' k stack) (st, step $ drop' k stack)\n        run a $ setArgsVM results vm1\n      else do\n        let\n          WasmFun {typeSig, localVars, funBody} = functions IM.! i\n          locals = initLocal <$> localVars\n          k = length $ fst typeSig\n        -- The `End` opcode is reintroduced at the ends of function calls, so\n        -- we know when to pop locals, and when to stop popping instructions\n        -- for `Return`.\n        run st vm { stack = drop' k stack, locs = IM.fromList (zip [0..] $ reverse (take' k stack) ++ locals):locs, insts = funBody:(End:head i1):tail i1 }\n    Return -> run st vm { insts = dropWhile ((End /=) . head) insts }\n    End -> run st vm { locs = tail locs, insts = i1 }\n    Set_local i -> run st vm {locs = IM.insert i (head stack) (head locs):tail locs, stack = tail stack, insts = i1}\n    Get_local i -> if i >= IM.size (head locs) then error $ \"BUG! bad local: \" ++ show(i, locs) else run st $ step $ head locs IM.! i:stack\n    Tee_local i -> run st vm {locs = IM.insert i (head stack) (head locs):tail locs, insts = i1}\n    Set_global i -> run st vm {globs = IM.insert i (head stack) globs, stack = tail stack, insts = i1}\n    Get_global i -> if i >= IM.size globs then error $ \"BUG! bad global: \" ++ show (i, globs)\n      else run st $ step $ globs IM.! i:stack\n    c@(I32_const _) -> run st $ step $ c:stack\n    c@(I64_const _) -> run st $ step $ c:stack\n    I32_xor -> binOp32 xor\n    I32_and -> binOp32 (.&.)\n    I32_or -> binOp32 (.|.)\n    I32_add -> binOp32 (+)\n    I32_sub -> binOp32 (-)\n    I32_mul -> binOp32 (*)\n    I32_div_s -> binOp32 div\n    I32_div_u -> binOp32U div\n    I32_rem_s -> binOp32 rem\n    I32_rem_u -> binOp32U rem\n    I32_shl -> binOp32U shiftL32\n    I32_rotl -> binOp32U rotateL32\n    I32_rotr -> binOp32U rotateR32\n    I32_shr_u -> binOp32U shiftR32U\n    I32_shr_s -> binOp32 shiftR32S\n    I32_ge_s -> binOp32 $ ((fromIntegral . fromEnum) .) . (>=)\n    I32_gt_s -> binOp32 $ ((fromIntegral . fromEnum) .) . (>)\n    I32_le_s -> binOp32 $ ((fromIntegral . fromEnum) .) . (<=)\n    I32_lt_s -> binOp32 $ ((fromIntegral . fromEnum) .) . (<)\n    I32_gt_u -> binOp32U $ (fromEnum .) . (>)\n    I32_ge_u -> binOp32U $ (fromEnum .) . (>=)\n    I32_lt_u -> binOp32U $ (fromEnum .) . (<)\n    I32_le_u -> binOp32U $ (fromEnum .) . (<=)\n    I32_ne -> binOp32 $ ((fromIntegral . fromEnum) .) . (/=)\n    I32_eq -> binOp32 $ ((fromIntegral . fromEnum) .) . (==)\n    I32_eqz -> let\n      (I32_const a:t) = stack\n      in run st $ step $ (I32_const $ fromIntegral $ fromEnum $ a == 0):t\n    I64_le_s -> boolBinOp64 (<=)\n    I64_lt_s -> boolBinOp64 (<)\n    I64_ge_s -> boolBinOp64 (>=)\n    I64_gt_s -> boolBinOp64 (>)\n    I64_le_u -> boolBinOp64U (<=)\n    I64_lt_u -> boolBinOp64U (<)\n    I64_ge_u -> boolBinOp64U (>=)\n    I64_gt_u -> boolBinOp64U (>)\n    I64_eq -> boolBinOp64 (==)\n    I64_add -> binOp64 (+)\n    I64_sub -> binOp64 (-)\n    I64_mul -> binOp64 (*)\n    I64_div_s -> binOp64 div\n    I64_div_u -> binOp64U div\n    I64_xor -> binOp64 xor\n    I64_and -> binOp64 (.&.)\n    I64_or -> binOp64 (.|.)\n    I64_rem_s -> binOp64 rem\n    I64_rem_u -> binOp64U rem\n    I64_shr_u -> binOp64 shiftR64U\n    I64_shr_s -> binOp64 shiftR64S\n    I64_shl -> binOp64 shiftL64\n    I64_rotr -> binOp64 rotateR64\n    I64_extend_s_i32 -> let\n      I32_const a = head stack\n      c = I64_const $ fromIntegral a\n      in run st $ step (c:tail stack)\n    I64_extend_u_i32 -> let\n      I32_const a = head stack\n      c = I64_const $ fromIntegral (fromIntegral a :: Word32)\n      in run st $ step (c:tail stack)\n    I32_wrap_i64 -> let\n      I64_const a = head stack\n      c = I32_const $ fromIntegral a\n      in run st $ step (c:tail stack)\n    I32_load8_u  _ o -> load32 1 o\n    I32_load16_u _ o -> load32 2 o\n    I32_load     _ o -> load32 4 o\n    I32_store8   _ o -> store32 1 o\n    I32_store16  _ o -> store32 2 o\n    I32_store    _ o -> store32 4 o\n    I64_store _ o -> do\n      let\n        I32_const addr = stack!!1\n        I64_const n = head stack\n      let mem' = putNum 8 (addr + fromIntegral o) n mem\n      run st (step $ drop 2 stack) { mem = mem'}\n    I64_load _ o -> do\n      let I32_const addr = head stack\n          c = I64_const $ getNum 8 (addr + fromIntegral o) mem\n      run st $ step (c:tail stack)\n\n    If _ t f -> let I32_const n = head stack in if n /= 0\n      then run st vm {stack = tail stack, insts = t:i1}\n      else run st vm {stack = tail stack, insts = f:i1}\n    Block _ bl -> run st vm {insts = bl:i1}\n    Loop _ bl -> run st vm {insts = bl:insts}\n    Br k -> run st vm {insts = drop (k + 1) insts}\n    Br_if k -> let (I32_const n:t) = stack in if n /= 0\n      then run st vm {stack = t, insts = drop (k + 1) insts}\n      else run st vm {stack = t, insts = i1}\n    Br_table as d -> do\n      let\n        n = fromIntegral n' where I32_const n' = head stack\n        k = if n < 0 || n >= length as then d else as!!n\n      run st vm {stack = tail stack, insts = drop (k + 1) insts}\n    Unreachable -> pure ([], (st, vm))\n    Drop -> run st $ step $ tail stack\n    Select -> do\n      let\n        [I32_const c, f, t] = take' 3 stack\n        r = if c /= 0 then t else f\n      run st $ step $ r:drop 3 stack\n    _ -> error $ \"TODO: \" ++ show (head $ head insts)\n    where\n    step newStack = vmNext { stack = newStack }\n    vmNext = vm { insts = i1 }\n    i1 = tail (head insts):tail insts\n    binOp32 f = run st $ step (c:drop 2 stack) where\n      (I32_const b:I32_const a:_) = stack\n      c = I32_const $ f a b\n    binOp32U f = run st $ step (c:drop 2 stack) where\n      (I32_const b:I32_const a:_) = stack\n      c = I32_const $ fromIntegral $ f (toU32 a) (toU32 b) where\n        toU32 n = (fromIntegral n :: Word32)\n    binOp64 f = run st $ step (c:drop 2 stack) where\n      (I64_const b:I64_const a:_) = stack\n      c = I64_const $ f a b\n    binOp64U f = run st $ step (c:drop 2 stack) where\n      (I64_const b:I64_const a:_) = stack\n      c = I64_const $ fromIntegral $ f (toU64 a) (toU64 b)\n    boolBinOp64 f = run st $ step (c:drop 2 stack) where\n      (I64_const b:I64_const a:_) = stack\n      c = I32_const $ fromIntegral $ fromEnum $ f a b\n    boolBinOp64U f = run st $ step (c:drop 2 stack) where\n      (I64_const b:I64_const a:_) = stack\n      c = I32_const $ fromIntegral $ fromEnum $ f (toU64 a) (toU64 b)\n    load32 sz off = run st $ step (I32_const (getNum sz (addr + fromIntegral off) mem):tail stack)\n      where I32_const addr = head stack\n    toU64 x = fromIntegral x :: Word64\n    store32 sz off = do\n      let (I32_const n:I32_const addr:_) = stack\n          mem' = putNum sz (addr + fromIntegral off) n mem\n      run st (step $ drop 2 stack) { mem = mem'}\n\n-- | Returns an exported function.\ngetExport :: String -> Hero -> Int\ngetExport f vm =\n  fromMaybe (error $ \"bad export: \" ++ f) $ lookup f $ exports $ wasm vm\n\n-- | Returns a function initially in the table.\ngetSlot :: Int32 -> Hero -> Int\ngetSlot i vm = either id (error $ \"must be called before invoke\") $\n  fromMaybe (error $ \"bad slot: \" ++ show i) $\n  IM.lookup (fromIntegral i) $ table vm\n\n-- | Interprets a wasm function.\ninvoke :: Monad m => VMEnv m a -> [(Int, WasmOp)] -> Int -> [WasmOp] -> (a, Hero) -> m ([WasmOp], (a, Hero))\ninvoke env gs k args (st, vm0) =\n  runImps env (st, (setArgsVM args vm) { insts = [[Call k]] })\n  where\n  Wasm{globalSection, dataSection, elemSection} = wasm vm0\n  vm = vm0\n    { locs = []\n    , stack = []\n    , globs = IM.fromList $ zip [0..] (head . snd <$> globalSection) ++ gs\n    , mem = IM.fromList $ concatMap strToAssocs dataSection\n    , table = IM.fromList $ concatMap mkElems elemSection\n    }\n  strToAssocs ([I32_const n], s) = zip [fromIntegral n..] $ fromIntegral <$> s\n  strToAssocs _ = error \"BUG!\"\n\nmkElems :: (Int, [Int]) -> [(Int, Either Int Int)]\nmkElems (offset, ns) = zip [offset..] $ Left <$> ns\n\n-- | Builds a Hero from imports and wasm binary.\ndecode :: Wasm -> Hero\ndecode w@Wasm{elemSection, types} = Hero\n  { locs = undefined\n  , stack = undefined\n  , insts = undefined\n  , globs = undefined\n  , mem = undefined\n  , table = IM.fromList $ concatMap mkElems elemSection\n  , sigs = IM.fromList $ zip [0..] types\n  , wasm = w\n  }\n\n-- | Place arguments on WebAssembly stack.\nsetArgsVM :: [WasmOp] -> Hero -> Hero\nsetArgsVM ls vm = vm { stack = reverse ls ++ stack vm }\n\n-- TODO: Check slot is in range.\nsetSlot :: Int32 -> Int -> Hero -> Hero\nsetSlot slot k vm = vm\n  { table = IM.insert (fromIntegral slot) (Right k) $ table vm }\n"
  },
  {
    "path": "src/Hero/HeroIO.hs",
    "content": "-- HeroIO is a wasm engine with a more natural interface for setting\n-- table entries to IO functions.\n--\n-- On principle, I'd like to keep a pure wasm engine,\n-- which is why HeroIO is distinct from Hero.\n\nmodule Hero.HeroIO\n  ( HeroIO\n  , decode\n  , invoke\n  , getMemory\n  , putMemory\n  , getSlot\n  , setSlot\n  , getExport\n  , globals\n  ) where\n\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.Word (Word8)\nimport Hero.Hero (Hero)\nimport qualified Hero.Hero as Hero\nimport WasmOp\n\nnewtype HeroAux = HeroAux { heroAux :: [WasmOp] -> HeroIO -> IO ([WasmOp], HeroIO) }\n\ntype HeroIO = (((String, String) -> HeroAux, IntMap HeroAux), Hero)\n\ndecode :: ((String, String) -> [WasmOp] -> HeroIO -> IO ([WasmOp], HeroIO)) -> Hero.Wasm -> HeroIO\ndecode imps w = ((HeroAux . imps, IM.empty), Hero.decode w)\n\ngetMemory :: Int32 -> HeroIO -> Word8\ngetMemory k (_, h) = Hero.getMemory k h\n\nputMemory :: Int32 -> Word8 -> HeroIO -> HeroIO\nputMemory k v (x, h) = (x, Hero.putMemory k v h)\n\ngetSlot :: Int32 -> HeroIO -> Int\ngetSlot k (_, h) = Hero.getSlot k h\n\ngetExport :: String -> HeroIO -> Int\ngetExport k (_, h) = Hero.getExport k h\n\nglobals :: HeroIO -> [(Int, WasmOp)]\nglobals (_, h) = Hero.globals h\n\nsetSlot :: Int32 -> ([WasmOp] -> HeroIO -> IO ([WasmOp], HeroIO)) -> HeroIO -> HeroIO\nsetSlot n f ((imps, x), vm) = ((imps, IM.insert k (HeroAux f) x), Hero.setSlot n k vm)\n  where k = IM.size x\n\ninvoke\n  :: [(Int, WasmOp)]  -- Globals.\n  -> Int              -- Function.\n  -> [WasmOp]         -- Arguments.\n  -> HeroIO           -- VM.\n  -> IO ([WasmOp], HeroIO)\ninvoke gs f as h = Hero.invoke (heroAux . fst (fst h), resolve) gs f as h\n\nresolve :: Int -> [WasmOp] -> HeroIO -> IO ([WasmOp], HeroIO)\nresolve k args h = (heroAux $ snd (fst h) IM.! k) args h\n"
  },
  {
    "path": "src/Hero/Parse.hs",
    "content": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NamedFieldPuns #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Hero.Parse (parseWasm, Wasm(..), ripWasm, elTable) where\n\n#ifdef __HASTE__\nimport qualified Data.Map.Strict as IM\nimport qualified Data.Set as IS\n#else\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\n#endif\nimport Control.Arrow\nimport Control.Monad\nimport qualified Data.ByteString as B\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport Data.Int\nimport Data.Maybe\nimport Data.Word\nimport WasmOp\n\n#ifdef __HASTE__\ntype IntMap = IM.Map Int\n#endif\n\ndata ExternalKind = Function | Table | Memory | Global\ntype FuncType = ([WasmType], [WasmType])\n\ndata Wasm = Wasm\n  { types :: [FuncType]\n  , imports :: [((String, String), FuncType)]\n  , decls :: [FuncType]\n  , tableSize :: Int\n  , memory :: [(Int, Maybe Int)]\n  , globalSection :: [((WasmType, Bool), [WasmOp])]\n  , exports :: [(String, Int)]\n  , start :: Maybe Int\n  , elemSection :: [(Int, [Int])]\n  , functions :: IntMap WasmFun\n  , dataSection :: [([WasmOp], [Word8])]\n  , dfnExports :: [(String, [WasmType])]\n  , martinTypes :: [[WasmType]]\n  , martinTypeMap :: [(Int, Int)]\n  , permaGlobals :: [(Int, WasmType)]\n  , persist :: [(Int, WasmType)]\n  , haskell :: String\n  } deriving Show\n\nemptyWasm :: Wasm\nemptyWasm = Wasm [] [] [] 0 [] [] [] Nothing [] IM.empty [] [] [] [] [] [] \"\"\n\ndata ByteParser a = ByteParser (ByteString -> Either String (a, ByteString))\n\ninstance Functor     ByteParser where fmap = liftM\ninstance Applicative ByteParser where {pure = return; (<*>) = ap}\ninstance Monad       ByteParser where\n  ByteParser f >>= g = ByteParser $ (good =<<) . f\n    where good (r, t) = let ByteParser gg = g r in gg t\n  return a = ByteParser $ \\s -> Right (a, s)\n\nnext :: ByteParser Word8\nnext = ByteParser f where\n  f s | B.null s = Left \"unexpected EOF\"\n      | otherwise = Right (B.head s, B.tail s)\n\nrepNext :: Int -> ByteParser ByteString\nrepNext n = ByteParser f where\n  f s | B.length s < n = Left \"missing bytes or size too large\"\n      | otherwise = Right $ B.splitAt n s\n\nisEof :: ByteParser Bool\nisEof = ByteParser f where f s = Right (B.null s, s)\n\nbad :: String -> ByteParser a\nbad = ByteParser . const . Left\n\nbyteParse :: ByteParser a -> ByteString -> Either String a\nbyteParse (ByteParser f) s = f s >>= (\\(w, t) ->\n  if B.null t then Right w else Left \"expected EOF\")\n\nremainder :: ByteParser ByteString\nremainder = ByteParser $ \\s -> Right (s, \"\")\n\nwasm :: ByteParser Wasm\nwasm = do\n  let\n    rep getInt task = getInt >>= (`replicateM` task)\n\n    varuint = fromIntegral <$> f 1 0 where\n      f :: Integer -> Integer -> ByteParser Integer\n      f m acc = do\n        d <- fromIntegral <$> next\n        if d > 127 then f (m * 128) $ (d - 128) * m + acc else pure $ d*m + acc\n\n    varint = f 1 0 where\n      f :: Integer -> Integer -> ByteParser Integer\n      f m acc = do\n        d <- fromIntegral <$> next\n        if d > 127 then f (m * 128) $ (d - 128) * m + acc else pure $\n          if d >= 64 then d*m + acc - 128*m else d*m + acc\n\n    varuint1 = varuint\n    varuint7 = next\n    varuint32 = varuint\n\n    varint7 :: ByteParser Int\n    varint7 = do\n      c <- fromIntegral <$> next\n      when (c >= 128) $ error \"bad varint7\"\n      pure $ if c >= 64 then c - 128 else c\n\n    varint32 :: ByteParser Int32\n    varint32 = fromIntegral <$> varint\n\n    varint64 :: ByteParser Int64\n    varint64 = fromIntegral <$> varint\n\n    lstr :: ByteParser String\n    lstr = rep varuint32 $ chr . fromIntegral <$> next\n\n    allType = do\n      t <- varuint7\n      case lookup t [(0x7f, I32), (0x7e, I64), (0x7d, F32), (0x7c, F64), (0x70, AnyFunc), (0x60, Func), (0x40, Nada)] of\n        Just ty -> pure ty\n        Nothing -> bad $ \"bad type: \" ++ show t\n\n    valueType = do\n      t <- allType\n      when (t `notElem` [I32, I64, F32, F64]) $ bad \"bad value_type\"\n      pure t\n\n    blockType = do\n      t <- allType\n      when (t `notElem` [I32, I64, F32, F64, Nada]) $ bad \"bad value_type\"\n      pure t\n\n    elemType = do\n      t <- allType\n      when (t /= AnyFunc) $ bad \"bad elem_type\"\n\n    externalKind = do\n      k <- varuint7\n      pure $ case k of\n        0 -> Function\n        1 -> Table\n        2 -> Memory\n        3 -> Global\n        _ -> error \"bad external_kind\"\n\n    funcType = do\n      form <- varint7\n      when (form /= -32) $ bad \"expected func type\"\n      paramTypes <- rep varuint32 valueType\n      returnTypes <- rep varuint1 valueType\n      pure (paramTypes, returnTypes)\n\n    functionCount w = length (imports w) + length (decls w)\n\n    sectType w = do\n      t <- rep varuint32 funcType\n      pure w { types = t }\n\n    sectImport w = do\n      ms <- rep varuint32 $ do\n        moduleStr <- lstr\n        fieldStr <- lstr\n        k <- externalKind\n        case k of\n          Function -> do\n            t <- varuint32\n            when (t > length (types w)) $ bad \"type out of range\"\n            pure ((moduleStr, fieldStr), types w !! t)\n          _ -> error \"TODO\"\n      pure w { imports = ms }\n\n    sectExport w = do\n      es <- rep varuint32 $ do\n        fieldStr <- lstr\n        k <- externalKind\n        t <- varuint32\n        case k of\n          Function -> do\n            when (t > functionCount w) $ bad \"function index out of range\"\n            pure $ Just (fieldStr, t)\n          Global -> pure Nothing\n          Memory -> pure Nothing\n          Table -> pure Nothing\n      pure w { exports = catMaybes es }\n\n    sectFunction w = do\n      sigs <- rep varuint32 $ do\n        t <- varuint32\n        when (t > length (types w)) $ bad \"type out of range\"\n        pure $ types w !! t\n      pure w { decls = sigs }\n\n    sectTable w = do\n      n <- varuint32\n      when (n > 1) $ bad \"MVP allows at most one table\"\n      if n == 0 then pure w else do\n        elemType\n        flags <- varuint1\n        m <- varuint32\n        when (flags == 1) $ void varuint32  -- TODO: Record maximum.\n        pure w { tableSize = m }\n\n    sectMemory w = do\n      n <- varuint32\n      when (n > 1) $ bad \"MVP allows at most one memory\"\n      if n == 0 then pure w else do\n        flags <- varuint1\n        initial <- varuint32\n        if flags > 0 then do\n          m <- varuint32\n          pure w { memory = [(initial, Just m)] }\n        else pure w { memory = [(initial, Nothing)] }\n\n    globalType = do\n      ty <- valueType\n      muta <- varuint1\n      pure (ty, muta > 0)\n\n    sectGlobal w = do\n      gs <- rep varuint32 $ do\n        gt <- globalType\n        x <- codeBlock w\n        pure (gt, x)\n      pure w { globalSection = gs }\n\n    sectStart w = do\n      i <- varuint32\n      when (i > functionCount w) $ bad \"function index out of range\"\n      pure w { start = Just i }\n\n    sectElement w = do\n      es <- rep varuint32 $ do\n        index <- varuint32\n        when (index /= 0) $ bad \"MVP allows at most one table\"\n        ~[I32_const offset] <- codeBlock w\n        ns <- rep varuint32 $ do\n          i <- varuint32\n          when (i > functionCount w) $ bad \"function index out of range\"\n          pure $ fromIntegral i\n        pure (fromIntegral offset, ns)\n      pure w { elemSection = es }\n\n    sectCode w = do\n      fs <- rep varuint32 $ do\n        _ <- varuint32  -- Size.\n        locals <- concat <$> rep varuint32 (replicate <$> varuint32 <*> valueType)\n        ops <- codeBlock w\n        pure (locals, ops)\n      pure w { functions = IM.fromList $ zip [length (imports w)..]\n        $ zipWith (\\a (b, c) -> WasmFun a b c) (decls w) fs }\n\n    sectData w = do\n      ds <- rep varuint32 $ do\n        index <- varuint32\n        when (index /= 0) $ bad \"MVP allows at most one memory\"\n        offset <- codeBlock w\n        (,) offset <$> rep varuint32 next\n      pure w { dataSection = ds }\n\n    martinFuncType = do\n      form <- varint7\n      when (form /= -32) $ bad \"expected func type\"\n      paramTypes <- rep varuint32 martinValueType\n      z <- varuint1\n      when (z /= 0) $ bad \"must have no return value\"\n      pure paramTypes\n\n    martinValueType = do\n      t <- varuint7\n      maybe (bad $ \"bad type: \" ++ show t) pure $ lookup t\n        [ (0x7f, I32)\n        , (0x7e, I64)\n        , (0x7d, F32)\n        , (0x7c, F64)\n        , (0x70, Ref \"Any\")  -- AnyFunc in standard wasm.\n        , (0x6f, Ref \"Actor\")\n        , (0x6e, Ref \"Module\")\n        , (0x6d, Ref \"Port\")\n        , (0x6c, Ref \"Databuf\")\n        , (0x6b, Ref \"Elem\")\n        ]\n\n    sectCustom w = do\n      name <- lstr\n      case name of\n        \"types\" -> do\n          t <- rep varuint32 martinFuncType\n          pure w { martinTypes = t }\n        \"typeMap\" -> do\n          tm <- rep varuint32 $ (,) <$> varuint32 <*> varuint32\n          pure w { martinTypeMap = tm }\n        \"persist\" -> do\n          g <- rep varuint32 $ do\n            tmp <- varuint7\n            when (tmp /= 3) $ bad \"expect 3\"\n            (,) <$> varuint32 <*> martinValueType\n          pure w { permaGlobals = g }\n        \"dfndbg\" -> remainder >> pure w\n        \"dfnhs\" -> do\n          void $ varuint32  -- Should be 1.\n          s <- remainder\n          pure w { haskell = chr . fromIntegral <$> B.unpack s }\n        _ -> remainder >> pure w\n\n    codeBlock :: Wasm -> ByteParser [WasmOp]\n    codeBlock w = do\n      opcode <- fromIntegral <$> varuint7\n      s <- if\n        | Just s <- lookup opcode $ zeroOperandOps -> pure s\n        | Just s <- lookup opcode [(0x02, Block), (0x03, Loop)] -> do\n          bt <- blockType\n          bl <- codeBlock w\n          pure $ s bt bl\n        | Just s <- lookup opcode [(0x20, Get_local), (0x21, Set_local), (0x22, Tee_local), (0x23, Get_global), (0x24, Set_global)] -> do\n          v <- varuint32\n          pure $ s v\n        | Just s <- lookup opcode [(0x28, I32_load), (0x29, I64_load), (0x2a, F32_load), (0x2b, F64_load), (0x2c, I32_load8_s), (0x2d, I32_load8_u), (0x2e, I32_load16_s), (0x2f, I32_load16_u), (0x30, I64_load8_s), (0x31, I64_load8_u), (0x32, I64_load16_s), (0x33, I64_load16_u), (0x34, I64_load32_s), (0x35, I64_load32_u), (0x36, I32_store), (0x37, I64_store), (0x38, F32_store), (0x39, F64_store), (0x3a, I32_store8), (0x3b, I32_store16), (0x3c, I64_store8), (0x3d, I64_store16), (0x3e, I64_store32)] -> do\n          flags <- varuint32\n          offset <- varuint32\n          pure $ s flags offset\n        | Just s <- lookup opcode [(0x0c, Br), (0x0d, Br_if)] -> do\n          v <- varuint32\n          pure $ s v\n        | otherwise -> case opcode of\n          0x04 -> do\n            bt <- blockType\n            bl <- codeBlock w\n            case last bl of\n              Else -> do\n                bl2 <- codeBlock w\n                pure $ If bt (init bl) bl2\n              _ -> pure $ If bt bl []\n          0x05 -> pure Else\n          0x0e -> do\n            n <- varuint32\n            tgts <- replicateM n varuint32\n            defTgt <- varuint32\n            pure $ Br_table tgts defTgt\n          0x41 -> do\n            i32 <- varint32\n            pure $ I32_const i32\n          0x42 -> do\n            i64 <- varint64\n            pure $ I64_const i64\n          0x10 -> do\n            i <- varuint32\n            pure $ Call i\n          0x11 -> do\n            i <- varuint32\n            ~ 0 <- varuint1\n            when (i >= length (types w)) $ bad \"Call_indirect index out of range\"\n            pure $ Call_indirect $ types w !! i\n          _ -> bad (\"bad opcode \" ++ show opcode)\n      if\n        | Else <- s -> pure [Else]\n        | End <- s -> pure []\n        | otherwise -> (s:) <$> codeBlock w\n\n    sect w = isEof >>= \\b -> if b then pure w else do\n      n <- varuint7\n      m <- varuint32\n      s <- repNext m\n      let\n        f = case n of\n          1 -> sectType\n          2 -> sectImport\n          3 -> sectFunction\n          4 -> sectTable\n          5 -> sectMemory\n          6 -> sectGlobal\n          7 -> sectExport\n          8 -> sectStart\n          9 -> sectElement\n          10 -> sectCode\n          11 -> sectData\n          0 -> sectCustom\n          _ -> pure\n      case byteParse (f w) s of\n        Left err -> bad err\n        Right w1 -> sect w1\n\n  header <- repNext 8  -- Header and version.\n  if header /= \"\\000asm\\001\\000\\000\\000\" then\n    bad \"bad header or version\"\n  else sect emptyWasm  -- Sections.\n\nparseWasm :: B.ByteString -> Either String Wasm\nparseWasm b = do\n  w@Wasm{imports, exports, martinTypeMap, martinTypes} <- byteParse wasm b\n  let\n    findType k\n      | Just mt <- lookup (k - length imports) martinTypeMap = martinTypes!!mt\n      -- Outputs make no sense for dfn, but we support them so we can use this\n      -- code more generally.\n      | k < length imports = fst $ snd $ imports !! k\n      | otherwise = fst $ decls w !! (k - length imports)\n  pure w { dfnExports = second findType <$> exports }\n\nripWasm :: [String] -> Wasm -> ([(String, Int)], [(Int, WasmFun)])\nripWasm es w = (zip es idxs, fMap)\n  where\n  Just idxs = mapM (`lookup` exports w) es\n  reachable = IS.elems $ followCalls idxs $ funBody <$> functions w\n  fMap = (\\i -> (i, functions w IM.! i)) <$> reachable\n\n-- Returns elements of table as\n-- association list of slot to (function index, function type).\nelTable :: Wasm -> [(Int, (Int, [WasmType]))]\nelTable (Wasm {martinTypes, martinTypeMap, elemSection, imports})\n  = second (\\n -> (n, maybe (error \"BUG! missing type\")\n    (martinTypes!!) $ lookup (n  - length imports) martinTypeMap)) <$> es where\n  es = concatMap (\\(offset, ns) -> zip [offset..] ns) elemSection\n"
  },
  {
    "path": "src/Hero/README.asciidoc",
    "content": "= The Hero Engine =\n\nA WebAssembly interpreter.\n\nLittle verification is performed.\n\nOnly supports a subset of the specification.\nIn particular, there is no support for floating point operations.\n"
  },
  {
    "path": "src/Hero/default.nix",
    "content": "{ pkgs ? import <nixpkgs> {}, compiler ? \"ghc822\" }:\nwith pkgs; let\n  dhc = haskellPackages.callCabal2nix \"dhc\" ../dhc {};\n  drv = haskellPackages.callCabal2nix \"hero\" ./. { inherit dhc; };\nin if pkgs.lib.inNixShell \n  then stdenv.lib.overrideDerivation drv.env (oldAttrs : \n    {\n      nativeBuildInputs = oldAttrs.nativeBuildInputs ++ [ cabal-install stack ];\n    })\n  else drv\n"
  },
  {
    "path": "src/Hero/hero.cabal",
    "content": "name:          hero\nversion:       0.0.0\nsynopsis:      WebAssembly interpreter.\nlicense:       GPL-3\nlicense-file:  LICENSE\ncopyright:     2017 DFINITY Stiftung\nauthor:        Ben Lynn <blynn@dfinity.org>\nmaintainer:    Ben Lynn <blynn@dfinity.org>\nstability:     Experimental\ncategory:      Interpreter\nhomepage:      https://github.com/dfinity/hero\nbug-reports:   https://github.com/dfinity/hero/issues\nbuild-type:    Simple\ncabal-version: >=1.10\n\nlibrary\n  build-depends:\n    base,\n    bytestring,\n    containers,\n    dhc,\n    parsec\n  default-language:\n    Haskell2010\n  exposed-modules:\n    Hero.Hero\n    Hero.HeroIO\n    Hero.Parse\n  ghc-options:\n    -O2\n    -Wall\n"
  },
  {
    "path": "src/Hero/test/Main.hs",
    "content": "import qualified Data.ByteString as B\nimport Test.HUnit\nimport Hero.Hero\nimport Data.Functor.Identity\n\nmain :: IO Counts\nmain = runTestTT test42\n\ntest42 :: Test\ntest42 = TestCase $ assertEqual \"i32.const 42\" \"42\" =<< pure (runTiny fortyTwo)\n\nrunTiny :: B.ByteString -> String\nrunTiny asm = runIdentity $ fst . snd <$>\n  invoke (syscall, undefined) [] (getExport \"e\" vm0) [] (\"\", vm0)\n  where\n  vm0 = decode $ either error id $ parseWasm asm\n  syscall (\"i\", \"f\") [I32_const a] (s, vm) = pure ([], (s ++ show a, vm))\n  syscall a b _ = error $ show (\"BUG! bad syscall\", a, b)\n\nfortyTwo :: B.ByteString\n-- Minimal wasm that exports a function returning the 32-bit integer 42.\n-- See https://crypto.stanford.edu/~blynn/lambda/wasm.html\nfortyTwo = B.pack\n  [0,97,115,109,1,0,0,0,1,8,2,96,1,127,0,96,0,0,2,7,1,1,105,1\n  ,102,0,0,3,2,1,1,7,5,1,1,101,0,1,10\n  ,8  -- Length of code section.\n  ,1\n  ,6  -- Length of function.\n  ,0\n  -- If the following is changed, then the above lengths should match.\n  ,65,42  -- 0x41, 42 means i32.const 42.\n  ,16,0,11]\n"
  },
  {
    "path": "src/Hero/test/bm.hs",
    "content": "-- Benchmark parsing.\nimport Criterion.Main\nimport qualified Data.ByteString as B\nimport Hero.Parse\nimport WasmOp\n\nmain :: IO ()\nmain = do\n  s <- B.getContents\n  defaultMain $ pure $ bench \"parse\" $ (`whnf` s) $ functions . either error id . parseWasm\n"
  },
  {
    "path": "src/Parse.hs",
    "content": "{-# LANGUAGE CPP #-}\nmodule Parse (parseDfnHs, lexOffside, TopLevel(..), QQuoter) where\n#ifndef __HASTE__\nimport qualified Data.ByteString.Char8 as B\nimport Data.ByteString.Short (ShortByteString, toShort)\n#endif\nimport Control.Arrow\nimport Control.Monad\nimport Data.Bool\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport Data.Maybe\nimport Text.Parsec\nimport Text.Parsec.Pos\n\nimport Ast\n\nsbs :: String -> ShortByteString\n#ifdef __HASTE__\nsbs = id\ntype ShortByteString = String\n#else\nsbs = toShort . B.pack\n#endif\n\ntype QQuoter = String -> String -> Either String String\ndata LexemeType = LexString | LexNumber | LexReserved | LexVar | LexCon | LexSpecial | LexVarSym | LexQual | IndError | IndCurly | IndAngle deriving (Eq, Show)\ntype Lexeme = (SourcePos, (LexemeType, String))\ntype Lexer = Parsec String QQuoter\n\nreservedIds :: [String]\nreservedIds = words \"class data default deriving do else foreign if import in infix infixl infixr instance let module newtype of then type where _\"\n\nreservedOps :: [String]\nreservedOps = [\"..\", \"::\", \"=\", \"|\", \"<-\", \"->\", \"=>\"]\n\nrawTok :: Lexer Lexeme\nrawTok = do\n  pos <- getPosition\n  r <- oxford <|> symbol <|> qId <|> num <|> special <|> str\n  filler\n  pure (pos, r)\n  where\n  lowId = do\n    s <- (:) <$> (lower <|> char '_') <*> many (alphaNum <|> oneOf \"_'\")\n    pure (if s `elem` reservedIds then LexReserved else LexVar, s)\n  uppId = do\n    s <- (:) <$> upper <*> many (alphaNum <|> oneOf \"_'\")\n    pure (LexCon, s)\n  qId = do\n    r@(_, m) <- lowId <|> uppId\n    try (do\n      void $ char '.'\n      (_, v) <- lowId <|> uppId\n      pure (LexQual, m ++ '.':v)) <|> pure r\n  num = do\n    s <- many1 digit\n    pure (LexNumber, s)\n  special = (,) LexSpecial <$> foldl1' (<|>) (string . pure <$> \"(),;[]`{}\")\n  symbol = do\n    s <- many1 (oneOf \"!#$%&*+./<=>?@\\\\^|-~:\")\n    pure (if s `elem` reservedOps then LexReserved else LexVarSym, s)\n  str = do\n    void $ char '\"'\n    s <- many $ (char '\\\\' >> escapes) <|> noneOf \"\\\"\"\n    void $ char '\"'\n    pure (LexString, s)\n  escapes = foldl1' (<|>)\n    [ char '\\\\' >> pure '\\\\'\n    , char '\"' >> pure '\"'\n    , char 'n' >> pure '\\n'\n    ]\n  oxford = do\n    q <- try $ between (char '[') (char '|') $ many alphaNum\n    s <- oxfordClose <|> more\n    qq <- getState\n    case qq q s of\n      Left err -> fail err\n      Right out -> pure (LexString, out)\n    where\n    oxfordClose = try (string \"|]\") >> pure \"\"\n    more = do\n      s <- innerOxford <|> (pure <$> anyChar)\n      (s ++) <$> (oxfordClose <|> more)\n    innerOxford = do\n      q <- try $ between (char '[') (char '|') $ many alphaNum\n      s <- oxfordClose <|> more\n      pure $ '[':q ++ ('|':s) ++ \"|]\"\n\nfiller :: Lexer ()\nfiller = void $ many $ void (char ' ') <|> nl <|> com\n  where\n  nl = (char '\\r' >> optional (char '\\n')) <|> void (oneOf \"\\n\\f\")\n  com = void $ between (try $ string \"--\") nl $ many $ noneOf \"\\r\\n\\f\"\n\n-- We use the `sourceColumn` of Parsec's SourcePos to record indentation.\ninsertIndents :: [Lexeme] -> [Lexeme]\ninsertIndents [] = []\n-- \"If the first lexeme of a module is not { or module, then it is preceded by\n-- {n} where n is the indentation of the lexeme.\"\ninsertIndents (x@(p, (LexSpecial, \"{\")):xs) = x:ii' (Just $ sourceLine p) xs\ninsertIndents xs@(h:_) = (fst h, (IndCurly, \"\")):ii' Nothing xs\n\nii' :: Maybe Line -> [Lexeme] -> [Lexeme]\nii' prevLine ls = case ls of\n-- \"If a let, where, do, or of keyword is not followed by the lexeme {, the\n-- token {n} is inserted after the keyword, where n is the indentation of the\n-- next lexeme if there is one, or 0 if the end of file has been reached.\"\n  [] -> []\n  [x]\n    | lwdo x -> mayAngle x ++ [(newPos \"\" 0 0, (IndCurly, \"\"))]\n    | otherwise -> mayAngle x\n  (x@(p, _):y:rest)\n    | lwdo x && not (isLBrace y) -> mayAngle x ++ (fst y, (IndCurly, \"\")):ii' Nothing (y:rest)\n    | otherwise -> mayAngle x ++ ii' (Just $ sourceLine p) (y:rest)\n-- \"Where the start of a lexeme is preceded only by white space on the same\n-- line, this lexeme is preceded by < n > where n is the indentation of the\n-- lexeme, provided that it is not, as a consequence of the first two rules,\n-- preceded by {n}.\"\n  where\n  mayAngle x@(p, _)\n    | Just l <- prevLine, l /= sourceLine p = [(p, (IndAngle, \"\")), x]\n    | otherwise = [x]\n  lwdo (_, (LexReserved, s)) | s `elem` [\"let\", \"where\", \"do\", \"of\"] = True\n  lwdo _ = False\n  isLBrace (_, (LexSpecial, \"{\")) = True\n  isLBrace _ = False\n\n-- Handle layout. See the L function in:\n--   https://www.haskell.org/onlinereport/haskell2010/haskellch10.html\nalgL :: [Lexeme] -> [Int] -> [Lexeme]\nalgL a@((p, (IndAngle, _)):ts) (m:ms)\n  | m == n = insL p \";\" $ algL ts (m:ms)\n  | m >  n = insL p \"}\" $ algL a ms\n  where n = sourceColumn p\nalgL ((_, (IndAngle, _)):ts) ms = algL ts ms\nalgL ((p, (IndCurly, _)):ts) (m:ms) | n > m = insL p \"{\" $ algL ts (n:m:ms)\n  where n = sourceColumn p\nalgL ((p, (IndCurly, _)):ts) [] | n > 0 = insL p \"{\" $ algL ts [n]\n  where n = sourceColumn p\nalgL ((p, (IndCurly, _)):ts) ms = insL p \"{\" $ insL p \"}\" $ algL ((p, (IndAngle, \"\")):ts) ms\nalgL ((p, (LexSpecial, \"}\")):ts) (0:ms) = insL p \"}\" $ algL ts ms\nalgL ((p, (LexSpecial, \"}\")):_) _ = [(p, (IndError, \"unmatched }\"))]\n-- We zero the source column of explicit open braces.\n-- TODO: It should be the other way around: implicit open braces should have\n-- their source column zeroed, while explicit ones should have their true\n-- column value. The check in `embrace` would have to be altered to match.\nalgL ((p, (LexSpecial, \"{\")):ts) ms = insL (setSourceColumn p 0) \"{\" $ algL ts (0:ms)\n-- See Note 5. We handle this case at a higher level, in `embrace`.\n-- algL (t:ts) (m:ms) | m /= 0 && bad = insL p \"}\" $ algL (t:ts) ms\nalgL (t:ts) ms = t : algL ts ms\nalgL [] [] = []\nalgL [] (m:ms) | m /= 0 = insL (newPos \"\" 0 0) \"}\" $ algL [] ms\n               | otherwise = [(newPos \"\" 0 0, (IndError, \"unmatched {\"))]\n\ninsL :: SourcePos -> String -> [Lexeme] -> [Lexeme]\ninsL p s = ((p, (LexSpecial, s)):)\n\ntype Parser = Parsec [Lexeme] ()\ndata TopLevel = Super (String, Ast)\n  | ClassDecl String String [(String, Type)]\n  | InstanceDecl [(String, String)] String Type [(String, Ast)]\n  | GenDecl (String, Type)\n  | DataDecl [(String, (Maybe (Int, Int), Type))]\n  | PublicDecl [String]\n  | StoreDecl [String]\n  deriving Show\n\narityFromType :: Type -> Int\narityFromType = f 0 where\n  f acc (_ :-> r) = f (acc + 1) r\n  f acc _ = acc\n\nheader :: Parser ([TopLevel], [Lexeme])\nheader = do\n  ps <- option [] $ want \"public\" >>\n    between (want \"(\") (want \")\") (var `sepBy` want \",\")\n  ss <- option [] $ want \"store\" >>\n    between (want \"(\") (want \")\") (var `sepBy` want \",\")\n  (,) [PublicDecl ps, StoreDecl ss] <$> getInput\n\ndata Stmt = Stmt Ast | StmtArr String Ast | StmtLet [(String, Ast)]\n\ntoplevels :: Parser [TopLevel]\ntoplevels = topDecls where\n  embrace p = do\n    m <- sourceColumn <$> getPosition\n    want \"{\"\n    let\n      next = ((:) <$> p <*> sepNext) <|> sepNext\n      sepNext = (want \";\" >> next) <|> (want \"}\" >> pure []) <|> autoClose\n      noMatch = obtain IndError >>= fail\n      autoClose = noMatch <|> do  -- Auto-insert \"}\".\n        when (m == 0) $ fail \"cannot implicitly close an explicit open brace\"\n        pure []\n    next\n  topDecls = embrace topDecl\n  topDecl = (want \"data\" >> simpleType)\n    <|> (want \"class\" >> classDecl)\n    <|> (want \"instance\" >> instanceDecl)\n    -- TODO: Left-factor genDecl and sc.\n    <|> (GenDecl <$> genDecl) <|> sc\n  classDecl = do\n    s <- con\n    t <- tyVar\n    want \"where\"\n    ms <- embrace cDecl\n    pure $ ClassDecl s t ms\n  instanceDecl = do\n    ctx <- option [] $ try $ do\n      ctxCls <- con\n      ctxVar <- tyVar\n      want \"=>\"\n      pure [(ctxCls, ctxVar)]\n    s <- con\n    t <- inst\n    want \"where\"\n    ms <- embrace iDecl\n    pure $ InstanceDecl ctx s t ms\n  inst = (TC <$> con)\n    <|> (TApp (TC \"[]\") . GV <$> between (want \"[\") (want \"]\") tyVar)\n  cDecl = genDecl\n  iDecl = do\n    (fun:args) <- funlhs\n    want \"=\"\n    ast <- expr\n    pure (fun, if null args then ast else Ast $ Lam args ast)\n  genDecl = try $ do\n    v <- var\n    want \"::\"\n    t <- typeExpr\n    pure (v, t)\n  simpleType = do\n    s <- con\n    args <- many tyVar\n    want \"=\"\n    let\n      t = foldl' TApp (TC s) $ GV <$> args\n      typeCon = do\n        c <- con\n        ts <- many atype\n        pure (c, foldr (:->) t ts)\n    typeCons <- typeCon `sepBy1` want \"|\"\n    pure $ DataDecl [(c, (Just (i, arityFromType typ), typ))\n      | (i, (c, typ)) <- zip [0..] typeCons]\n  typeExpr = foldr1 (:->) <$> btype `sepBy1` want \"->\"\n  btype = foldl1' TApp <$> many1 atype\n  -- Unsupported: [] (->) (,{,}) constructors.\n  atype = (TC <$> con)\n    <|> (GV <$> tyVar)\n    <|> (TApp (TC \"[]\") <$> between (want \"[\") (want \"]\") typeExpr)\n    <|> (parenType <$> between (want \"(\") (want \")\") (typeExpr `sepBy` want \",\"))\n  parenType [x] = x\n  parenType xs  = foldr1 TApp $ TC \"()\":xs\n  sc = Super <$> letDefn\n  funlhs = do\n    v0 <- var\n    scOp v0 <|> ((v0:) <$> many var)\n  scOp l = do\n    op <- varSym\n    r <- var\n    pure [op, l, r]\n  expr = infixExp\n  infixExp = bin 0 False\n  bin 10 _ = lexp\n  bin prec isR = rec False =<< bin (prec + 1) False where\n    rec isL m = try (do\n      o <- varSym <|> between (want \"`\") (want \"`\") var\n      let (a, p) = fixity o\n      when (p /= prec) $ fail \"\"\n      case a of\n        LAssoc -> do\n          when isR $ fail \"same precedence, mixed associativity\"\n          n <- bin (prec + 1) False\n          rec True $ Ast $ Ast (Ast (Var o) :@ m) :@ n\n        NAssoc -> do\n          n <- bin (prec + 1) False\n          pure $ Ast $ Ast (Ast (Var o) :@ m) :@ n\n        RAssoc -> do\n          when isL $ fail \"same precedence, mixed associativity\"\n          n <- bin prec True\n          pure $ Ast $ Ast (Ast (Var o) :@ m) :@ n\n      ) <|> pure m\n  letDefn = do\n    (fun:args) <- funlhs\n    want \"=\"\n    ast <- expr\n    pure (fun, if null args then ast else Ast $ Lam args ast)\n  doExpr = do\n    want \"do\"\n    ss <- embrace stmt\n    case ss of\n      [] -> fail \"empty do block\"\n      _ -> desugarDo ss\n  desugarDo [Stmt x] = pure x\n  desugarDo [] = fail \"do block must end with expression\"\n  desugarDo (h:rest) = do\n    body <- desugarDo rest\n    pure $ Ast $ case h of\n      Stmt x -> Ast (Ast (Var \">>=\") :@ x) :@ Ast (Lam [\"_\"] body)\n      StmtArr v x -> Ast (Ast (Var \">>=\") :@ x) :@ Ast (Lam [v] body)\n      StmtLet ds -> Let ds body\n  stmt = stmtLet <|> do\n    v <- expr\n    lArrStmt v <|> pure (Stmt v)\n  lArrStmt v = want \"<-\" >> case v of\n    Ast (Var s) -> StmtArr s <$> expr\n    _ -> fail \"want variable on left of (<-)\"\n  stmtLet = do\n    want \"let\"\n    ds <- embrace letDefn\n    (want \"in\" >> Stmt . Ast . Let ds <$> expr) <|> pure (StmtLet ds)\n  letExpr = do\n    ds <- between (want \"let\") (want \"in\") $ embrace letDefn\n    Ast . Let ds <$> expr\n  caseExpr = do\n    x <- between (want \"case\") (want \"of\") expr\n    as <- embrace alt\n    when (null as) $ fail \"empty case\"\n    pure $ Ast $ Cas x as\n  alt = do\n    p <- expr\n    want \"->\"\n    x <- expr\n    pure (p, x)\n  -- TODO: Introduce patterns to deal with _.\n  lambda = fmap Ast $ Lam <$> between (want \"\\\\\") (want \"->\") (many1 $ var <|> uscore) <*> expr\n  lexp = lambda <|> caseExpr <|> letExpr <|> doExpr <|> foldl1' ((Ast .) . (:@)) <$> many1 atom\n  uscore = want \"_\" >> pure \"_\"\n  atom = qvar\n    <|> (Ast . Var <$> uscore)\n    <|> (Ast . Var <$> var)\n    <|> (Ast . Var <$> con)\n    <|> num <|> str <|> lis <|> enumLis <|> tup\n  tup = do\n    xs <- between (want \"(\") (want \")\") $ expr `sepBy` want \",\"\n    pure $ case xs of  -- Abuse Pack to represent tuples.\n      [] -> Ast $ Pack 0 0\n      [x] -> x\n      _ -> foldl' ((Ast .) . (:@)) (Ast $ Pack 0 $ length xs) xs\n\n  -- TODO: Left-factor lis and enumLis.\n  lis = try $ do\n    items <- between (want \"[\") (want \"]\") $ expr `sepBy` want \",\"\n    pure $ foldr (\\a b -> Ast (Ast (Ast (Var \":\") :@ a) :@ b)) (Ast $ Var \"[]\") items\n  enumLis = try $ between (want \"[\") (want \"]\") $ do\n    a <- expr\n    want \"..\"\n    b <- expr\n    pure $ Ast $ Ast (Ast (Var \"enumFromTo\") :@ a) :@ b\n\n  splitDot s = second tail $ splitAt (fromJust $ elemIndex '.' s) s\n  qvar = Ast . uncurry Qual . splitDot <$> obtain LexQual\n  con = obtain LexCon\n  num = Ast . I . read <$> obtain LexNumber\n  str = Ast . S . sbs <$> obtain LexString\n  tyVar = varId\n\nvar :: Parser String\nvar = varId <|> try (between (want \"(\") (want \")\") varSym)\n\nvarId :: Parser String\nvarId = obtain LexVar\n\nvarSym :: Parser String\nvarSym = obtain LexVarSym\n\nobtain :: LexemeType -> Parser String\nobtain t = token show fst f where\n  f (_, (t', s)) = bool Nothing (Just s) $ t == t'\n\nwant :: String -> Parser ()\nwant s = void $ token show fst f where\n  f (_, (LexString, _)) = Nothing\n  f (_, (_, t)) | s == t = Just ()\n  f _ = Nothing\n\ndata Associativity = LAssoc | RAssoc | NAssoc deriving (Eq, Show)\n\nstandardFixities :: Map String (Associativity, Int)\nstandardFixities = M.fromList $ concatMap (f . words)\n  [ \"infixl 9 !!\"\n  , \"infixr 9 .\"\n  , \"infixr 8 ^ ^^ **\"\n  , \"infixl 7 * / div mod rem quot\"\n  , \"infixl 6 + -\"\n  , \"infixr 5 : ++\"\n  , \"infix 4 == /= < <= > >= elem notElem\"\n  , \"infixr 3 &&\"\n  , \"infixr 2 ||\"\n  , \"infixl 1 >> >>=\"\n  , \"infixr 0 $ $! seq\"\n  ]\n  where\n    f (assoc:prec:ops) = flip (,) (parseAssoc assoc, read prec) <$> ops\n    f _ = undefined\n    parseAssoc \"infix\"  = NAssoc\n    parseAssoc \"infixl\" = LAssoc\n    parseAssoc \"infixr\" = RAssoc\n    parseAssoc _ = error \"BUG! bad associativity\"\n\nfixity :: String -> (Associativity, Int)\nfixity o = fromMaybe (LAssoc, 9) $ M.lookup o standardFixities\n\nparseDfnHs :: QQuoter -> String -> Either ParseError [TopLevel]\nparseDfnHs qq s = do\n  lexStream <- runParser (filler >> many rawTok) qq \"\" s\n  (r0, rest) <- parse header \"\" lexStream\n  fmap (r0 ++) $ parse toplevels \"\" $ (`algL` []) $ insertIndents rest\n\nlexOffside :: String -> Either ParseError [String]\nlexOffside s = map (snd . snd) . (`algL` []) . insertIndents\n  <$> runParser (filler >> many rawTok) (\\_ _ -> Left \"no qq\") \"\" s\n"
  },
  {
    "path": "src/Std.hs",
    "content": "module Std (stdBoost) where\n\nimport Boost\nimport DHC\nimport WasmOp\n\nsp, hp, bp :: Int\n[sp, hp, bp] = [0, 1, 2]\n\nstdBoost :: Boost\nstdBoost = Boost\n  -- No Wasm Imports\n  []\n  -- Prelude definitions.\n  (unlines\n  [ \"data Bool = False | True\"\n  , \"data Maybe a = Nothing | Just a\"\n  , \"data Either a b = Left a | Right b\"\n  , \"fst p = case p of (x, y) -> x\"\n  , \"snd p = case p of (x, y) -> y\"\n  , \"f . g = \\\\x -> f (g x)\"\n  , \"flip f = \\\\x y -> f y x\"\n  , \"fromJust m = case m of {Just x -> x}\"\n  , \"maybe n j m = case m of {Just x -> j x; Nothing -> n}\"\n  , \"f >> g = f >>= \\\\_ -> g\"\n  , \"bool f t b = case b of {False -> f; True ->t}\"\n  , \"when b t = bool (pure ()) t b\"\n  , \"f $ x = f x\"\n  , \"id x = x\"\n  , \"class Eq a where (==) :: a -> a -> Bool\"\n  , \"class Monad m where\"\n  , \"  (>>=) :: m a -> (a -> m b) -> m b\"\n  , \"  pure :: a -> m a\"\n  -- Generates call_indirect ops.\n  , \"class Message a where callSlot :: I32 -> a -> IO ()\"\n  , \"class Storage a where\"\n  , \"  atoAnyRef :: a -> I32\"\n  , \"  bfromAnyRef :: I32 -> a\"\n  , \"  ctoUnboxed :: a -> Unboxed a\"\n  , \"  dfromUnboxed :: Unboxed a -> a\"\n  , \"set x y = fst x $ ctoUnboxed y\"\n  , \"get x = snd x >>= pure . dfromUnboxed\"\n  , \"instance Monad Maybe where\"\n  , \"  x >>= f = case x of { Nothing -> Nothing; Just a -> f a }\"\n  , \"  pure x = Just x\"\n  , \"io_pure x rw = (x, rw)\"\n  , \"io_bind f g rw = let {p = f rw} in case p of (a, rw1) -> g a rw1\"\n  , \"instance Monad IO where\"\n  , \"  (>>=) = io_bind\"\n  , \"  pure = io_pure\"\n  , \"instance Eq Int where (==) = eq_Int\"\n  , \"instance Eq String where (==) = eq_String\"\n  , \"instance Eq a => Eq [a] where a == b = case a of { [] -> case b of {[] -> True; w -> False}; (x:xs) -> case b of { [] -> False; (y:ys) -> (x == y) && (xs == ys) } }\"\n  ])\n  -- Haskell functions defined in wasm.\n  [ (\"+\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Int\", intAsm I64_add))\n  , (\"-\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Int\", intAsm I64_sub))\n  , (\"*\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Int\", intAsm I64_mul))\n  , (\"div\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Int\", intAsm I64_div_s))\n  , (\"mod\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Int\", intAsm I64_rem_s))\n  , (\"<\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Bool\", cmpAsm I64_lt_s))\n  , (\">\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Bool\", cmpAsm I64_gt_s))\n  , (\"<=\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Bool\", cmpAsm I64_le_s))\n  , (\">=\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Bool\", cmpAsm I64_ge_s))\n  , (\"&&\", (TC \"Bool\" :-> TC \"Bool\" :-> TC \"Bool\", boolAsm I32_and))\n  , (\"||\", (TC \"Bool\" :-> TC \"Bool\" :-> TC \"Bool\", boolAsm I32_or))\n  , (\"++\", (TC \"String\" :-> TC \"String\" :-> TC \"String\", catAsm))\n  , (\"slice\", (TC \"Int\" :-> TC \"String\" :-> TApp (TC \"()\") (TApp (TC \"String\") (TC \"String\")), sliceAsm))\n  , (\"undefined\", (a, [Unreachable, End]))\n\n  -- It'd be nice if these two were somehow only available internally to DHC.\n  , (\"eq_Int\", (TC \"Int\" :-> TC \"Int\" :-> TC \"Bool\", cmpAsm I64_eq))\n  , (\"eq_String\", (TC \"String\" :-> TC \"String\" :-> TC \"Bool\", strEqAsm))\n\n  -- Programmers cannot call the following directly.\n  -- We keep their types around for various checks.\n  , (\"#rundict\", (TC \"I32\" :-> GV \"a\" :-> GV \"b\", runDictAsm))\n  ]\n  -- Internal wasm helpers.\n  [ (\"#memcpyhp\", (([I32, I32], []), memcpyhpAsm))\n  , (\"#notmemcmp\", (([I32, I32, I32], [I32]), notmemcmpAsm))\n  ]\n  where\n    a = GV \"a\"\n\nintAsm :: QuasiWasm -> [QuasiWasm]\nintAsm op =\n  [ Custom $ ReduceArgs 2\n  , Get_global sp  -- PUSH [[sp + 4] + 8]\n  , I32_load 2 4\n  , I64_load 3 8\n  , Get_global sp  -- sp = sp + 8\n  , I32_const 8\n  , I32_add\n  , Set_global sp\n  , Get_global sp  -- PUSH [[sp] + 8]\n  , I32_load 2 0\n  , I64_load 3 8\n  , op\n  , Custom $ CallSym \"#pushint\"\n  , I32_const 12  -- UpdatePopEval 2\n  , Custom $ CallSym \"#updatepopeval\"\n  , End\n  ]\ncmpAsm :: QuasiWasm -> [QuasiWasm]\ncmpAsm op =\n  [ Custom $ ReduceArgs 2\n  , Get_global hp  -- [hp] = TagSum\n  , tag_const TagSum\n  , I32_store 2 0\n  -- [hp + 4] = [[sp + 4] + 8] == [[sp + 8] + 8]\n  , Get_global hp  -- PUSH hp\n  , Get_global sp  -- PUSH [[sp + 4] + 8]\n  , I32_load 2 4\n  , I64_load 3 8\n  , Get_global sp  -- PUSH [[sp + 8] + 8]\n  , I32_load 2 8\n  , I64_load 3 8\n  , op\n  , I32_store 2 4\n  , Get_global sp  -- [sp + 8] = hp\n  , Get_global hp\n  , I32_store 2 8\n  , Get_global sp  -- sp = sp + 4\n  , I32_const 4\n  , I32_add\n  , Set_global sp\n  , Get_global hp  -- hp = hp + 8\n  , I32_const 8\n  , I32_add\n  , Set_global hp\n  , I32_const 12  -- UpdatePopEval 2\n  , Custom $ CallSym \"#updatepopeval\"\n  , End\n  ]\nboolAsm :: QuasiWasm -> [QuasiWasm]\nboolAsm op =\n  [ Custom $ ReduceArgs 2\n  , Get_global hp  -- [hp] = TagSum\n  , tag_const TagSum\n  , I32_store 2 0\n  -- [hp + 4] = [[sp + 4] + 4] `op` [[sp + 8] + 4]\n  , Get_global hp\n  , Get_global sp\n  , I32_load 2 4\n  , I32_load 2 4\n  , Get_global sp\n  , I32_load 2 8\n  , I32_load 2 4\n  , op\n  , I32_store 2 4\n  , Get_global sp  -- [sp + 8] = hp\n  , Get_global hp\n  , I32_store 2 8\n  , Get_global sp  -- sp = sp + 4\n  , I32_const 4\n  , I32_add\n  , Set_global sp\n  , Get_global hp  -- hp = hp + 8\n  , I32_const 8\n  , I32_add\n  , Set_global hp\n  , I32_const 12  -- UpdatePopEval 2\n  , Custom $ CallSym \"#updatepopeval\"\n  , End\n  ]\ncatAsm :: [QuasiWasm]\ncatAsm =\n  [ Custom $ ReduceArgs 2\n  , Get_global sp  -- PUSH sp\n  , Get_global hp  -- PUSH hp\n  , Get_global hp  -- [hp] = TagString\n  , tag_const TagString\n  , I32_store 2 0\n  , Get_global hp -- [hp + 4] = hp + 16\n  , Get_global hp\n  , I32_const 16\n  , I32_add\n  , I32_store 2 4\n  , Get_global hp -- [hp + 8] = 0\n  , I32_const 0\n  , I32_store 2 8\n  , Get_global hp -- [hp + 12] = [[sp + 4] + 12] + [[sp + 8] + 12]\n  , Get_global sp\n  , I32_load 2 4\n  , I32_load 2 12\n  , Get_global sp\n  , I32_load 2 8\n  , I32_load 2 12\n  , I32_add\n  , I32_store 2 12\n  , Get_global hp  -- hp = hp + 16\n  , I32_const 16\n  , I32_add\n  , Set_global hp\n  , Get_global sp  -- memcpyhp ([[sp + 4] + 4] + [[sp + 4] + 8]) [[sp + 4] + 12]\n  , I32_load 2 4\n  , I32_load 2 4\n  , Get_global sp\n  , I32_load 2 4\n  , I32_load 2 8\n  , I32_add\n  , Get_global sp\n  , I32_load 2 4\n  , I32_load 2 12\n  , Custom $ CallSym \"#memcpyhp\"\n  , Get_global sp  -- memcpyhp ([[sp + 8] + 4] + [[sp + 8] + 8]) [[sp + 8] + 12]\n  , I32_load 2 8\n  , I32_load 2 4\n  , Get_global sp\n  , I32_load 2 8\n  , I32_load 2 8\n  , I32_add\n  , Get_global sp\n  , I32_load 2 8\n  , I32_load 2 12\n  , Custom $ CallSym \"#memcpyhp\"\n  , I32_store 2 8  -- [sp + 8] = old_hp  ; Via POPs.\n  , Get_global sp  -- sp = sp + 4\n  , I32_const 4\n  , I32_add\n  , Set_global sp\n  , I32_const 0  -- Align hp.\n  , Get_global hp\n  , I32_sub\n  , I32_const 3\n  , I32_and\n  , Get_global hp\n  , I32_add\n  , Set_global hp\n  , I32_const 12  -- UpdatePopEval 2\n  , Custom $ CallSym \"#updatepopeval\"\n  , End\n  ]\nmemcpyhpAsm :: [QuasiWasm]\nmemcpyhpAsm =\n  [ Loop Nada  -- while (local1 != 0) {\n    [ Get_local 1\n    , I32_eqz\n    , Br_if 1\n    , Get_local 1  -- local1 = local1 - 1\n    , I32_const 1\n    , I32_sub\n    , Set_local 1\n    , Get_global hp  -- [hp].8 = [local0].8\n    , Get_local 0\n    , I32_load8_u 0 0\n    , I32_store8 0 0\n    , Get_local 0  -- local0 = local0 + 1\n    , I32_const 1\n    , I32_add\n    , Set_local 0\n    , Get_global hp  -- hp = hp + 1\n    , I32_const 1\n    , I32_add\n    , Set_global hp\n    , Br 0\n    ]\n  , End\n  ]\nstrEqAsm :: [QuasiWasm]\nstrEqAsm =\n  [ Custom $ ReduceArgs 2\n  , Get_global sp  -- PUSH sp\n  , Get_global hp  -- PUSH hp\n  , Get_global hp  -- [hp] = TagSum\n  , tag_const TagSum\n  , I32_store 2 0\n  , Get_global hp  -- [hp + 4] = 0\n  , I32_const 0\n  , I32_store 2 4\n  , Get_global sp  -- bp = [[sp + 4] + 12]\n  , I32_load 2 4\n  , I32_load 2 12\n  , Set_global bp\n\n  , Block Nada\n    [ Get_global sp  -- if bp /= [[sp + 8] + 12] then break\n    , I32_load 2 8\n    , I32_load 2 12\n    , Get_global bp\n    , I32_ne\n    , Br_if 0\n\n    , Get_global hp  -- PUSH hp\n    , Get_global sp  -- notmemcmp ([[sp + 4] + 4] + [[sp + 4] + 8]) ([[sp + 8] + 4] + [[sp + 8] + 8]) bp\n    , I32_load 2 4\n    , I32_load 2 4\n    , Get_global sp\n    , I32_load 2 4\n    , I32_load 2 8\n    , I32_add\n    , Get_global sp\n    , I32_load 2 8\n    , I32_load 2 4\n    , Get_global sp\n    , I32_load 2 8\n    , I32_load 2 8\n    , I32_add\n    , Get_global bp\n    , Custom $ CallSym \"#notmemcmp\"\n    , I32_store 2 4  -- [hp + 4] = result  ; Via POP.\n    ]\n  , I32_store 2 8  -- [sp + 8] = old_hp  ; Via POPs.\n  , Get_global sp  -- sp = sp + 4\n  , I32_const 4\n  , I32_add\n  , Set_global sp\n  , Get_global hp  -- hp = hp + 8\n  , I32_const 8\n  , I32_add\n  , Set_global hp\n  , I32_const 12  -- UpdatePopEval 2\n  , Custom $ CallSym \"#updatepopeval\"\n  , End\n  ]\nnotmemcmpAsm :: [QuasiWasm]\nnotmemcmpAsm =\n  [ Loop Nada  -- while (local2 != 0) {\n    [ Get_local 2\n    , I32_eqz\n    , If Nada [ I32_const 1 , Return ] []\n    , Get_local 2  -- local2 = local2 - 1\n    , I32_const 1\n    , I32_sub\n    , Set_local 2\n    , Get_local 0  -- [local0].8 /= [local1].8 ?\n    , I32_load8_u 0 0\n    , Get_local 1\n    , I32_load8_u 0 0\n    , I32_ne\n    , If Nada [ I32_const 0 , Return ] []\n    , Get_local 0  -- local0 = local0 + 1\n    , I32_const 1\n    , I32_add\n    , Set_local 0\n    , Get_local 1  -- local1 = local1 + 1\n    , I32_const 1\n    , I32_add\n    , Set_local 1\n    , Br 0\n    ]\n  , Unreachable\n  , End\n  ]\nsliceAsm :: [QuasiWasm]\nsliceAsm =\n  [ Custom $ ReduceArgs 2\n  -- TODO: Handle lengths out of range.\n  , Get_global sp  -- bp = [[sp + 4] + 8]\n  , I32_load 2 4\n  , I32_load 2 8\n  , Set_global bp\n  , Get_global hp  -- [hp] = TagSum | (2 << 8)\n  , I32_const $ fromIntegral $ fromEnum TagSum + 256 * 2\n  , I32_store 2 0\n  , Get_global hp  -- [hp + 4] = 0\n  , I32_const 0\n  , I32_store 2 4\n  , Get_global hp  -- [hp + 8] = hp + 16\n  , Get_global hp\n  , I32_const 16\n  , I32_add\n  , I32_store 2 8\n  , Get_global hp  -- [hp + 12] = hp + 32\n  , Get_global hp\n  , I32_const 32\n  , I32_add\n  , I32_store 2 12\n  , Get_global hp  -- [hp + 16] = TagString\n  , tag_const TagString\n  , I32_store 2 16\n  , Get_global hp  -- [hp + 20] = [[sp + 8] + 4]\n  , Get_global sp\n  , I32_load 2 8\n  , I32_load 2 4\n  , I32_store 2 20\n  , Get_global hp  -- [hp + 24] = [[sp + 8] + 8]\n  , Get_global sp\n  , I32_load 2 8\n  , I32_load 2 8\n  , I32_store 2 24\n  , Get_global hp  -- [hp + 28] = bp\n  , Get_global bp\n  , I32_store 2 28\n  , Get_global hp  -- [hp + 32] = TagString\n  , tag_const TagString\n  , I32_store 2 32\n  , Get_global hp  -- [hp + 36] = [[sp + 8] + 4]\n  , Get_global sp\n  , I32_load 2 8\n  , I32_load 2 4\n  , I32_store 2 36\n  , Get_global hp  -- [hp + 40] = [[sp + 8] + 8] + bp\n  , Get_global sp\n  , I32_load 2 8\n  , I32_load 2 8\n  , Get_global bp\n  , I32_add\n  , I32_store 2 40\n  , Get_global hp  -- [hp + 44] = [[sp + 8] + 12] - bp\n  , Get_global sp\n  , I32_load 2 8\n  , I32_load 2 12\n  , Get_global bp\n  , I32_sub\n  , I32_store 2 44\n  , Get_global sp  -- sp = sp + 4\n  , I32_const 4\n  , I32_add\n  , Set_global sp\n  , Get_global sp  -- [sp + 4] = hp\n  , Get_global hp\n  , I32_store 2 4\n  , Get_global hp  -- hp = hp + 48\n  , I32_const 48\n  , I32_add\n  , Set_global hp\n  , I32_const 12  -- UpdatePopEval 2\n  , Custom $ CallSym \"#updatepopeval\"\n  , End\n  ]\n\n-- | Runs a method at a given index of a given dictionary.\n-- Expects [I32, Coproduct] on top of the stack (both in normal form).\n-- The coproduct represents a dictionary of methods for an instance of a\n-- typeclass, e.g. the dictionary for the Monad instace of Maybe is:\n--\n--   Copro 0 [Maybe->>=, Maybe-pure]\nrunDictAsm :: [QuasiWasm]\nrunDictAsm =\n  [ Get_global sp  -- [sp + 12] = [[sp + 8] + [[sp + 4] + 4]]\n  , Get_global sp\n  , I32_load 2 8\n  , Get_global sp\n  , I32_load 2 4\n  , I32_load 2 4\n  , I32_add\n  , I32_load 2 0\n\n  , I32_store 2 12\n  , Get_global sp  -- sp = sp + 8\n  , I32_const 8\n  , I32_add\n  , Set_global sp\n  , Custom $ CallSym \"#eval\"\n  , End\n  ]\n"
  },
  {
    "path": "src/WasmOp.hs",
    "content": "{-# LANGUAGE CPP #-}\n#ifdef __HASTE__\n{-# LANGUAGE PackageImports #-}\n#endif\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveGeneric #-}\nmodule WasmOp\n  ( WasmType(..), CustomWasmOp(..), WasmOp, zeroOperandOps, rZeroOps\n  , followCalls, renumberCalls, WasmFun(..)\n  ) where\n#ifdef __HASTE__\nimport \"mtl\" Control.Monad.State\nimport qualified Data.Set as IS\nimport qualified Data.Map.Strict as IM\n#else\nimport Control.Monad.State\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\n#endif\nimport Data.Binary (Binary)\nimport Data.Int\nimport Data.Void\nimport GHC.Generics (Generic)\n\n#ifdef __HASTE__\ntype IntMap = IM.Map Int\ntype IntSet = IS.Set Int\n#endif\n\ndata WasmType = I32 | I64 | F32 | F64 | Func | AnyFunc | Nada\n  | Ref String  -- Custom types used by Dfinity.\n  deriving (Read, Show, Eq, Ord, Generic)\ninstance Binary WasmType\n\ndata WasmFun = WasmFun\n  { typeSig :: ([WasmType], [WasmType])\n  , localVars :: [WasmType]\n  , funBody :: [WasmOp]\n  } deriving Show\n\n-- Much of this file was generated from:\n--   http://webassembly.org/docs/binary-encoding/\n\ndata CustomWasmOp a = Custom a\n  | I32_eqz | I32_eq | I32_ne | I32_lt_s | I32_lt_u | I32_gt_s | I32_gt_u | I32_le_s | I32_le_u | I32_ge_s | I32_ge_u | I64_eqz | I64_eq | I64_ne | I64_lt_s | I64_lt_u | I64_gt_s | I64_gt_u | I64_le_s | I64_le_u | I64_ge_s | I64_ge_u | F32_eq | F32_ne | F32_lt | F32_gt | F32_le | F32_ge | F64_eq | F64_ne | F64_lt | F64_gt | F64_le | F64_ge | I32_clz | I32_ctz | I32_popcnt | I32_add | I32_sub | I32_mul | I32_div_s | I32_div_u | I32_rem_s | I32_rem_u | I32_and | I32_or | I32_xor | I32_shl | I32_shr_s | I32_shr_u | I32_rotl | I32_rotr | I64_clz | I64_ctz | I64_popcnt | I64_add | I64_sub | I64_mul | I64_div_s | I64_div_u | I64_rem_s | I64_rem_u | I64_and | I64_or | I64_xor | I64_shl | I64_shr_s | I64_shr_u | I64_rotl | I64_rotr | F32_abs | F32_neg | F32_ceil | F32_floor | F32_trunc | F32_nearest | F32_sqrt | F32_add | F32_sub | F32_mul | F32_div | F32_min | F32_max | F32_copysign | F64_abs | F64_neg | F64_ceil | F64_floor | F64_trunc | F64_nearest | F64_sqrt | F64_add | F64_sub | F64_mul | F64_div | F64_min | F64_max | F64_copysign | I32_wrap_i64 | I32_trunc_s_f32 | I32_trunc_u_f32 | I32_trunc_s_f64 | I32_trunc_u_f64 | I64_extend_s_i32 | I64_extend_u_i32 | I64_trunc_s_f32 | I64_trunc_u_f32 | I64_trunc_s_f64 | I64_trunc_u_f64 | F32_convert_s_i32 | F32_convert_u_i32 | F32_convert_s_i64 | F32_convert_u_i64 | F32_demote_f64 | F64_convert_s_i32 | F64_convert_u_i32 | F64_convert_s_i64 | F64_convert_u_i64 | F64_promote_f32 | I32_reinterpret_f32 | I64_reinterpret_f64 | F32_reinterpret_i32 | F64_reinterpret_i64\n  | I32_load Int Int | I64_load Int Int | F32_load Int Int | F64_load Int Int | I32_load8_s Int Int | I32_load8_u Int Int | I32_load16_s Int Int | I32_load16_u Int Int | I64_load8_s Int Int | I64_load8_u Int Int | I64_load16_s Int Int | I64_load16_u Int Int | I64_load32_s Int Int | I64_load32_u Int Int | I32_store Int Int | I64_store Int Int | F32_store Int Int | F64_store Int Int | I32_store8 Int Int | I32_store16 Int Int | I64_store8 Int Int | I64_store16 Int Int | I64_store32 Int Int\n  | Unreachable | Nop | Else | End | Return\n  | Block WasmType [CustomWasmOp a] | Loop WasmType [CustomWasmOp a] | If WasmType [CustomWasmOp a] [CustomWasmOp a]\n  | Get_local Int | Set_local Int | Tee_local Int | Get_global Int | Set_global Int\n  | I32_const Int32 | I64_const Int64 | F32_const Float | F64_const Double\n  | Br_table [Int] Int\n  | Br Int | Br_if Int\n  | Call Int\n  | Call_indirect ([WasmType], [WasmType])\n  | Drop | Select\n  deriving (Show, Eq, Functor)\n\ntype WasmOp = CustomWasmOp Void\n\nzeroOperandOps :: [(Int, WasmOp)]\nzeroOperandOps = cmpOps ++ ariOps ++ crops ++ others ++ parametrics where\n  cmpOps = [(0x45, I32_eqz), (0x46, I32_eq), (0x47, I32_ne), (0x48, I32_lt_s), (0x49, I32_lt_u), (0x4a, I32_gt_s), (0x4b, I32_gt_u), (0x4c, I32_le_s), (0x4d, I32_le_u), (0x4e, I32_ge_s), (0x4f, I32_ge_u), (0x50, I64_eqz), (0x51, I64_eq), (0x52, I64_ne), (0x53, I64_lt_s), (0x54, I64_lt_u), (0x55, I64_gt_s), (0x56, I64_gt_u), (0x57, I64_le_s), (0x58, I64_le_u), (0x59, I64_ge_s), (0x5a, I64_ge_u), (0x5b, F32_eq), (0x5c, F32_ne), (0x5d, F32_lt), (0x5e, F32_gt), (0x5f, F32_le), (0x60, F32_ge), (0x61, F64_eq), (0x62, F64_ne), (0x63, F64_lt), (0x64, F64_gt), (0x65, F64_le), (0x66, F64_ge)]\n  ariOps = [(0x67, I32_clz), (0x68, I32_ctz), (0x69, I32_popcnt), (0x6a, I32_add), (0x6b, I32_sub), (0x6c, I32_mul), (0x6d, I32_div_s), (0x6e, I32_div_u), (0x6f, I32_rem_s), (0x70, I32_rem_u), (0x71, I32_and), (0x72, I32_or), (0x73, I32_xor), (0x74, I32_shl), (0x75, I32_shr_s), (0x76, I32_shr_u), (0x77, I32_rotl), (0x78, I32_rotr), (0x79, I64_clz), (0x7a, I64_ctz), (0x7b, I64_popcnt), (0x7c, I64_add), (0x7d, I64_sub), (0x7e, I64_mul), (0x7f, I64_div_s), (0x80, I64_div_u), (0x81, I64_rem_s), (0x82, I64_rem_u), (0x83, I64_and), (0x84, I64_or), (0x85, I64_xor), (0x86, I64_shl), (0x87, I64_shr_s), (0x88, I64_shr_u), (0x89, I64_rotl), (0x8a, I64_rotr), (0x8b, F32_abs), (0x8c, F32_neg), (0x8d, F32_ceil), (0x8e, F32_floor), (0x8f, F32_trunc), (0x90, F32_nearest), (0x91, F32_sqrt), (0x92, F32_add), (0x93, F32_sub), (0x94, F32_mul), (0x95, F32_div), (0x96, F32_min), (0x97, F32_max), (0x98, F32_copysign), (0x99, F64_abs), (0x9a, F64_neg), (0x9b, F64_ceil), (0x9c, F64_floor), (0x9d, F64_trunc), (0x9e, F64_nearest), (0x9f, F64_sqrt), (0xa0, F64_add), (0xa1, F64_sub), (0xa2, F64_mul), (0xa3, F64_div), (0xa4, F64_min), (0xa5, F64_max), (0xa6, F64_copysign)]\n  crops = [(0xa7, I32_wrap_i64), (0xa8, I32_trunc_s_f32), (0xa9, I32_trunc_u_f32), (0xaa, I32_trunc_s_f64), (0xab, I32_trunc_u_f64), (0xac, I64_extend_s_i32), (0xad, I64_extend_u_i32), (0xae, I64_trunc_s_f32), (0xaf, I64_trunc_u_f32), (0xb0, I64_trunc_s_f64), (0xb1, I64_trunc_u_f64), (0xb2, F32_convert_s_i32), (0xb3, F32_convert_u_i32), (0xb4, F32_convert_s_i64), (0xb5, F32_convert_u_i64), (0xb6, F32_demote_f64), (0xb7, F64_convert_s_i32), (0xb8, F64_convert_u_i32), (0xb9, F64_convert_s_i64), (0xba, F64_convert_u_i64), (0xbb, F64_promote_f32), (0xbc, I32_reinterpret_f32), (0xbd, I64_reinterpret_f64), (0xbe, F32_reinterpret_i32), (0xbf, F64_reinterpret_i64)]\n  others = [(0x00, Unreachable), (0x01, Nop), (0x0b, End), (0x0f, Return)]\n  parametrics = [(0x1a, Drop), (0x1b, Select)]\n\nrZeroOps :: [(WasmOp, Int)]\nrZeroOps = (\\(a, b) -> (b, a)) <$> zeroOperandOps\n\nfollowCalls :: [Int] -> IntMap [WasmOp] -> IntSet\nfollowCalls ns m = execState (go ns) $ IS.fromList ns where\n  go :: [Int] -> State IntSet ()\n  go (n:rest) = do\n    maybe (pure ()) tr $ IM.lookup n m\n    go rest\n  go [] = pure ()\n  tr (w:rest) = do\n    case w of\n      Call i -> do\n        s <- get\n        when (IS.notMember i s) $ do\n          put $ IS.insert i s\n          go [i]\n      Loop _ b -> tr b\n      Block _ b -> tr b\n      If _ t f -> do\n        tr t\n        tr f\n      _ -> pure ()\n    tr rest\n  tr [] = pure ()\n\nrenumberCalls :: IntMap Int -> [WasmOp] -> [WasmOp]\nrenumberCalls m ws = case ws of\n  [] -> []\n  (w:rest) -> ren w:rec rest\n  where\n  rec = renumberCalls m\n  ren w = case w of\n    Call i -> Call $ m IM.! i\n    Loop t b -> Loop t $ rec b\n    Block t b -> Block t $ rec b\n    If t a b -> If t (rec a) (rec b)\n    x -> x\n"
  },
  {
    "path": "test/Main.hs",
    "content": "{-# LANGUAGE QuasiQuotes #-}\nimport Control.Arrow\nimport Control.Monad\nimport Data.Bits\nimport qualified Data.ByteString as B\nimport Data.ByteString.Char8 (unpack)\nimport Data.ByteString.Short (ShortByteString, fromShort, toShort)\nimport Data.Char (chr)\nimport Data.Int\nimport Data.List (foldl')\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Word\nimport Test.HUnit\nimport Text.Heredoc (here, there)\nimport Asm\nimport Boost\nimport DHC\nimport Hero.Hero\nimport Parse\nimport SoloSyscall\nimport Std\nimport Demo\n\ndata Node = NInt Int64 | NString ShortByteString | NAp Int Int | NGlobal Int String | NInd Int | NCon Int [Int] | RealWorld [String] deriving Show\n\n-- | Interprets G-Machine instructions.\ngmachine :: String -> String\ngmachine prog = if \"main_\" `M.member` funs then\n    go (Right <$> [PushGlobal \"main_\", Eval]) [] M.empty\n  else\n    go (Right <$> [PushGlobal \"main\", MkAp, Eval]) [0] $ M.singleton 0 $ RealWorld []\n  where\n  drop' n as | n > length as = error \"BUG!\"\n             | otherwise     = drop n as\n  (funs, m) = either error id $ hsToGMachine toyBoost prog\n  toyBoost = Boost [] []\n    -- We'll intercept `putStr` so there's no need for an implementation.\n    [ (\"putStr\", (TC \"String\" :-> TApp (TC \"IO\") (TC \"()\"), []))\n    , (\"putInt\", (TC \"Int\" :-> TApp (TC \"IO\") (TC \"()\"), []))\n    ] []\n  arity \"putStr\" = 1\n  arity \"putInt\" = 1\n  arity s | Just a <- M.lookup s funs = a\n  arity s = arityFromType $ fst $ fromJust $ lookup s $ boostPrims stdBoost\n  go (fOrIns:rest) s h = either prim exec fOrIns where\n    k = M.size h\n    heapAdd x = M.insert k x h\n    intInt f = go rest (k:srest) $ heapAdd $ NInt $ f x y where\n      (s0:s1:srest) = s\n      NInt x = h M.! s0\n      NInt y = h M.! s1\n    intCmp f = go rest (k:srest) $ heapAdd $ NCon (fromEnum $ f x y) [] where\n      (s0:s1:srest) = s\n      NInt x = h M.! s0\n      NInt y = h M.! s1\n    boolOp f = go rest (k:srest) $ heapAdd $ NCon (f x y) [] where\n      (s0:s1:srest) = s\n      NCon x [] = h M.! s0\n      NCon y [] = h M.! s1\n    rwAdd msg heap | RealWorld ms <- heap M.! 0 =\n      M.insert 0 (RealWorld $ ms ++ [msg]) heap\n    rwAdd _ _ = error \"BUG! Expect RealWorld at 0 on heap\"\n    prims = M.fromList\n      [ (\"+\", intInt (+))\n      , (\"-\", intInt (-))\n      , (\"*\", intInt (*))\n      , (\"div\", intInt div)\n      , (\"mod\", intInt mod)\n      , (\"eq_Int\", intCmp (==))\n      , (\"<\", intCmp (<))\n      , (\">\", intCmp (>))\n      , (\"&&\", boolOp min)\n      , (\"||\", boolOp max)\n      , (\"++\", let\n        (s0:s1:srest) = s\n        NString str0 = h M.! s0\n        NString str1 = h M.! s1\n        t = toShort $ fromShort str0 <> fromShort str1\n        in go rest (k:srest) $ heapAdd $ NString t)\n      , (\"putStr\", let\n        k1 = k + 1\n        (s0:srest) = s\n        NString str = h M.! s0\n        in go rest (k:srest) $ rwAdd (unpack $ fromShort str) $ M.insert k1 (NCon 0 []) $ heapAdd $ NCon 0 [k1, 0])\n      , (\"#rundict\", let\n        (s0:s1:srest) = s\n        NInt n = h M.! s0\n        NCon _ as = h M.! s1\n        in go rest (as!!(fromIntegral (n - 8) `div` 4):srest) h)\n      ]\n    prim g | Just f <- M.lookup g prims = f\n           | otherwise = error $ \"unsupported: \" ++ g\n    exec ins = case ins of\n      Trap -> \"UNREACHABLE\"\n      PushInt n -> go rest (k:s) $ heapAdd $ NInt n\n      PushRef n -> go rest (k:s) $ heapAdd $ NInt $ fromIntegral n\n      PushString str -> go rest (k:s) $ heapAdd $ NString str\n      Push n -> go rest (s!!n:s) h\n      PushGlobal v -> go rest (k:s) $ heapAdd $ NGlobal (arity v) v\n      MkAp -> let (s0:s1:srest) = s in go rest (k:srest) $ heapAdd $ NAp s0 s1\n      UpdateInd n -> go rest (tail s) $ M.insert (s!!(n + 1)) (NInd $ head s) h\n      UpdatePopEval n -> go (Right Eval:rest) (drop' (n + 1) s) $ M.insert (s!!(n + 1)) (NInd $ head s) h\n      Alloc n -> go rest ([k..k+n-1]++s) $ M.union h $ M.fromList $ zip [k..k+n-1] (repeat $ NInd 0)\n      Slide n -> let (s0:srest) = s in go rest (s0:drop' n srest) h\n      Copro n l -> go rest (k:drop' l s) $ heapAdd $ NCon n $ take l s\n      Split _ -> let\n        (s0:srest) = s\n        NCon _ as = h M.! s0\n        in go rest (as ++ srest) h\n      Eval -> case h M.! head s of\n        NInd i -> go (Right Eval:rest) (i:tail s) h\n        NAp a _ -> go (Right Eval:rest) (a:s) h\n        NGlobal n g -> let\n          p | g == \"putStr\" = [Right $ Push 0, Right Eval, Left \"putStr\", Right $ Slide 3]\n            | Just is <- M.lookup g m = Right <$> is\n            | M.member g prims = (Right <$> concat (replicate n [Push $ n - 1, Eval]))\n              ++ [Left g, Right $ UpdatePopEval n]\n            | otherwise = error $ \"unsupported: \" ++ g\n          debone i = r where NAp _ r = h M.! i\n          in go (p ++ rest) ((debone <$> take n (tail s)) ++ drop' n s) h\n        _ -> go rest s h\n      Casejump alts -> let\n        x = case h M.! head s of\n          NCon n _ -> fromIntegral n\n          _ -> undefined\n        body = case lookup (Just x) alts of\n          Just b -> b\n          _ -> fromJust $ lookup Nothing alts\n        in go ((Right <$> body) ++ rest) s h\n      _ -> error \"unsupported\"\n  go [] [r] h\n    | \"main_\" `M.member` funs = case h M.! r of\n      NInt n -> show n\n      NCon n _ -> \"Pack \" ++ show n\n      NString s -> show s\n      _ -> error \"expect NInt or NCon on stack\"\n    | NCon 0 [_, o] <- h M.! r, RealWorld out <- h M.! o = show out\n  go [] s h = error $ \"bad stack: \" ++ show (s, h)\n\ngmachineTests :: [Test]\ngmachineTests = (\\(result, source) -> TestCase $\n  assertEqual source result $ gmachine source) <$>\n    -- Test cases from Peyton Jones and Lester,\n    -- \"Implementing Functional Languages; a tutorial\".\n    -- Each case either contains a `main` function of type `IO a`, or\n    -- a pure `main_` function which we reduce to WHNF.\n    [ (\"81\", \"square x = x * x; main_ = square (square 3)\")\n    , (\"3\", \"i x = x; main_ = i 3\")\n    , (\"3\", \"id = s k k; s x y z = x z (y z); k x y = x; main_ = id 3\")\n    , (\"3\", \"id = s k k; s x y z = x z (y z); k x y = x; twice f x = f (f x);\"\n      ++ \"main_ = twice twice twice id 3\")\n    , (\"3\", \"i x = x; twice f x = f (f x ); main_ = twice (i i i) 3\")\n    , (\"4\", concat\n      [ \"cons a b cc cn = cc a b; nil cc cn = cn; hd list = list k abort;\"\n      , \"abort = abort;\"\n      , \"k x y = x; k1 x y = y;\"\n      , \"tl list = list k1 abort;\"\n      -- The following fail to type-check:\n      --   infinite x = cons x (infinite x);\n      -- so we make do with a fixed list.\n      , \"main_ = hd (tl (cons 3 (cons 4 nil)))\"\n      ])\n    , (\"17\", \"main_ = 4*5+(2-5)\")\n    , (\"8\", \"twice f x = f (f x); inc x = x + 1; main_ = twice twice inc 4\")\n      -- Change list representation so that `length` can be typed.\n    , (\"3\", concat\n      [ \"length xs = xs (\\\\h a -> 1 + a) 0;\"\n      , \"cons h t c n = c h(t c n); nil c n = n;\"\n      , \"main_ = length (cons 3 (cons 3 (cons 3 nil)))\"\n      ])\n    , (\"120\", \"fac n = case n == 0 of { True -> 1; False -> (n * fac (n - 1)) }\\nmain_ = fac 5\")\n    , (\"2\", \"gcd a b = case a == b of { True -> a; False -> case a < b of\"\n      ++ \" { True -> gcd b a; False -> gcd b (a - b) } }; main_ = gcd 6 10\")\n    , (\"9\", \"nfib n = case n < 2 of { True -> 1; False -> 1 + nfib (n - 1) + nfib (n - 2) }; main_ = nfib 4\")\n    , (\"Pack 1\", \"main_ = 2 + 2 == 4\")\n    , (\"Pack 0\", \"main_ = 2 + 2 == 5\")\n    , (\"Pack 1\", \"main_ = [1,1,2] == [1,1,2]\")\n    , (\"Pack 1\", \"main_ = [[1,1],[2]] == [[1,1],[2]]\")\n    , (\"Pack 0\", \"main_ = [[1],[2]]   == [[1,1],[2]]\")\n    , (\"Pack 0\", \"main_ = (==) [[1,1],[2]] [[1,3],[2]]\")\n    , (\"Pack 1\", \"f x = x == x; main_ = f [1,2,3]\")\n    , (\"1\", \"main_ = (case 3 > 2 of True -> 1; False -> 0)\")\n    , (\"\\\"Hello, World\\\"\", \"main_ = \\\"Hello\\\" ++ \\\", \\\" ++ \\\"World\\\"\")\n    , (show [\"hello\"], \"main = putStr \\\"hello\\\"\")\n    , (show [\"hello\", \"world\"], \"main = putStr \\\"hello\\\" >>= \\\\x -> putStr \\\"world\\\"\")\n    , (show [\"hello\", \"hello\"], \"putHello = putStr \\\"hello\\\" ; main = putHello >>= \\\\_ -> putHello\")\n    , (show [\"hello\", \"world\"], unlines\n      [ \"main = do\"\n      , \"  putStr \\\"hello\\\"\"\n      , \"  putStr \\\"world\\\"\"\n      ])\n    , (show [\"one\", \"two\", \"three\"], unlines\n      [ \"main = do\"\n      , \"  putStr \\\"one\\\"\"\n      , \"  putStr \\\"two\\\"\"\n      , \"  putStr \\\"three\\\"\"\n      ])\n    , (show [\"hello\", \"world\"], unlines\n      [ \"main = do\"\n      , \"  x <- pure \\\"world\\\"\"\n      , \"  putStr \\\"hello\\\"\"\n      , \"  putStr x\"\n      ])\n    ]\n\nlexOffsideTests :: [Test]\nlexOffsideTests = (\\(result, source) -> TestCase $\n  assertEqual source (Right result) $ lexOffside source) <$>\n    [ ([\"{\", \"main\", \"=\", \"foo\", \"}\"], \"main = foo\")\n    , ([\"{\", \"x\", \"=\", \"1\", \";\", \"y\", \"=\", \"2\", \"}\"], \"x = 1\\ny = 2\")\n    , ([\"{\", \"main\", \"=\", \"do\", \"{\", \"foo\", \";\", \"bar\", \"}\", \"}\"], unlines\n      [ \"main = do\"\n      , \"  foo\"\n      , \"  bar\"\n      ])\n    -- The following lexes \"incorrectly\" (the parentheses and curly braces\n    -- are improperly nested), but is fixed in the parser. See Note 5 of\n    -- https://www.haskell.org/onlinereport/haskell2010/haskellch10.html\n    , (words \"{ f x = ( case x of { True -> 1 ; False -> 0 ) } }\",\n      \"f x = (case x of True -> 1; False -> 0)\")\n    ]\n\ndemoCases :: [(String, String)]\ndemoCases = second (\"public (main)\\n\" ++) <$>\n  [ (\"Hello, World!\\n\", \"main = putStr \\\"Hello, World!\\\\n\\\"\")\n  , (\"Hello, Quasi!\\n\", \"main = putStr [here|Hello, Quasi!\\n|]\")\n  , (\"9876543210\", \"main = putInt 9876543210\")\n  , (\"42\", unlines\n    [ \"main = putInt (f 42)\"\n    , \"f :: Int -> Int\"\n    , \"f x = x\"\n    ])\n  , (\"123\", unlines\n    [ \"main = maybe undefined putInt $ do\"\n    , \"  x <- (Just 5 >>= (\\\\x -> Just $ x * 24))\"\n    , \"  pure (x + 3)\"\n    ])\n  , (\"314\", unlines\n    [ \"data List x = Nil | Cons x (List x)\"\n    , \"main = f (Cons 3 (Cons 1 (Cons 4 Nil)))\"\n    , \"f l = case l of\"\n    , \"  Nil -> putStr \\\"\\\"\"\n    , \"  Cons n rest -> do\"\n    , \"    putInt n\"\n    , \"    f rest\"\n    ])\n  , (\"1123459\", unlines\n    [ \"data Tree a = Nil | Node a (Tree a) (Tree a)\"\n    , \"main = pr (f Nil [3, 1, 4, 1, 5, 9, 2])\"\n    , \"f t l = case l of\"\n    , \"  [] -> t\"\n    , \"  x:xs -> f (ins x t) xs\"\n    , \"ins x t = case t of\"\n    , \"  Nil -> Node x Nil Nil\"\n    , \"  Node y a b -> case x > y of\"\n    , \"    True -> Node y a (ins x b)\"\n    , \"    False -> Node y (ins x a) b\"\n    , \"pr t = case t of\"\n    , \"  Nil -> pure ()\"\n    , \"  Node x a b -> do\"\n    , \"    pr a\"\n    , \"    putInt x\"\n    , \"    pr b\"\n    ])\n  , (\"hello\", [here|\nf $ x = f x\nxs =  [(271828, \"l\"), (318310, \"he\"), (618034, \"o\")]\nmain = do\n  putStr $ fromJust $ lookup 318310 xs\n  putStr $ fromJust $ lookup 271828 xs\n  putStr $ fromJust $ lookup 271828 xs\n  putStr $ fromJust $ lookup 618034 xs\nlookup n xs = case xs of\n  [] -> Nothing\n  ((k, v):rest) -> case k == n of\n    True -> Just v\n    False -> lookup n rest\n|])\n  , (unlines\n    [ \"recursion with fix: 10000\"\n    , \"5! + (10 + 20 + 30 + 40 + 50) = 270\"\n    ], [there|test/example.hs|])\n  ]\n\ndemoTests :: [Test]\ndemoTests = (\\(result, source) -> TestCase $ runDemo source >>= assertEqual source result) <$> demoCases\n\n-- Could be turned into a runhaskell-like tool with:\n--\n--   main = putStr =<< runDemo =<< getContents\nrunDemo :: String -> IO String\nrunDemo src = case hsToWasm demoBoost src of\n  Left err -> error err\n  Right ints -> let\n    vm = decode $ either error id $ parseWasm $ B.pack $ fromIntegral <$> ints\n    in fst . snd <$> invoke (sys, undefined) [] (getExport \"main\" vm) [] (\"\", vm)\n  where\n  sys (\"system\", \"putStr\") [I32_const ptr, I32_const len] (s, vm) =\n    pure ([], (s ++ [chr $ getNum 1 (ptr + i) vm | i <- [0..len - 1]], vm))\n  sys (\"system\", \"putInt\") [I64_const i] (s, vm) = pure ([], (s ++ show i, vm))\n  sys _ _ _ = error \"BUG! bad syscall\"\n\naltWebTests :: [Test]\naltWebTests = (\\(result, source) -> TestCase $ runAltWeb source >>= assertEqual source result) <$> demoCases\n\n-- Alternate host for putStr and putInt using SoloSyscall.\naltWebBoost :: Boost\naltWebBoost = Boost [((\"dhc\", \"system\"), ([I32, I32, I32], []))]\n  []\n  (second (uncurry genSyscallFromType) <$>\n  [ (\"putStr\", (21, TC \"String\" :-> io (TC \"()\")))\n  , (\"putInt\", (22, TC \"Int\" :-> io (TC \"()\")))\n  ])\n  []\n  where io = TApp (TC \"IO\")\n\nrunAltWeb :: String -> IO String\nrunAltWeb src = case hsToWasm altWebBoost src of\n  Left err -> error err\n  Right ints -> let\n    vm = decode $ either error id $ parseWasm $ B.pack $ fromIntegral <$> ints\n    in fst . snd <$> invoke (altWebSys, undefined) [] (getExport \"main\" vm) [] (\"\", vm)\n\naltWebSys :: (String, String) -> [WasmOp] -> (String, Hero) -> IO ([WasmOp], (String, Hero))\naltWebSys (\"dhc\", \"system\") [I32_const n, I32_const sp, I32_const hp] (s, vm)\n  | n == 21 = do\n    when (getTag /= 6) $ error \"BUG! want String\"\n    let\n      ptr = getNum 4 (addr + 4) vm\n      off = getNum 4 (addr + 8) vm\n      slen = getNum 4 (addr + 12) vm\n    pure ([], (s ++ [chr $ getNum 1 (ptr + off + i) vm | i <- [0..slen - 1]]\n      , putNum 4 hp (5 :: Int)\n      $ putNum 4 (hp + 4) (0 :: Int)\n      $ putNum 4 sp hp\n      $ putNum 4 (sp - 4) (hp + 8)\n      vm))\n  | n == 22 = do\n    when (getTag /= 3) $ error \"BUG! want Int\"\n    pure ([], (s ++ show (getNum 8 (addr + 8) vm :: Int)\n      , putNum 4 hp (5 :: Int)\n      $ putNum 4 (hp + 4) (0 :: Int)\n      $ putNum 4 sp hp\n      $ putNum 4 (sp - 4) (hp + 8)\n      vm))\n  | otherwise = error $ \"BUG! bad syscall \" ++ show n\n  where\n    addr = getNum 4 (sp + 4) vm :: Int32\n    getTag = getNum 1 addr vm :: Int\naltWebSys _ _ _ = error \"BUG! bad syscall \"\n\nmain :: IO Counts\nmain = runTestTT $ TestList $ lexOffsideTests ++ gmachineTests ++ demoTests ++ altWebTests\n\ngetNum :: (Integral n) => Int -> Int32 -> Hero -> n\ngetNum w addr vm = sum $ zipWith (*) bs ((256^) <$> [(0 :: Int)..]) where\n  bs = fromIntegral . (`getMemory` vm) . (addr +) <$> [0..fromIntegral w-1]\n\nputNum :: (Integral n) => Int -> Int32 -> n -> Hero -> Hero\nputNum w addr n vm = foldl' f vm [0..w-1] where\n  f m k = putMemory (addr + fromIntegral k) (getByte k) m\n  getByte k = fromIntegral $ ((fromIntegral n :: Word64) `shiftR` (8*k)) .&. 255\n"
  },
  {
    "path": "test/SoloSyscall.hs",
    "content": "-- A simple syscall scheme.\n--\n-- We expect a single import function:\n--   dhc.system : I32 -> I32 -> I32 -> ()\n-- which expects the syscall number, heap pointer, and stack pointer.\n\nmodule SoloSyscall (genSyscall, genSyscallFromType) where\n\nimport Data.Int\nimport Boost\nimport DHC\nimport WasmOp\n\nsp, hp :: Int\n[sp, hp] = [0, 1]\n\ngenSyscallFromType :: Int64 -> Type -> (Type, [QuasiWasm])\ngenSyscallFromType n t = (t, genSyscall (isIO t) n $ fromIntegral $ arityFromType t)\n\nisIO :: Type -> Bool\nisIO (_ :-> u) = isIO u\nisIO (TC \"IO\" `TApp` _) = True\nisIO _ = False\n\n-- | Generates the WebAssembly for `dhc.system n sp hp` where `n` is the\n-- syscall number and `m` is the number of arguments the syscall expects.\n-- We evaluate `m` arguments on the heap to WHNF.\n-- For pure syscalls we return the result.\n-- For impure syscalls we return the tuple (result, #RealWorld).\n-- TODO: Get rid of #RealWorld token.\ngenSyscall :: Bool -> Int64 -> Int64 -> [QuasiWasm]\ngenSyscall impure svc argCount =\n  [ Custom $ ReduceArgs $ fromIntegral argCount\n  , I32_const $ fromIntegral svc\n  , Get_global sp\n  , Get_global hp\n  , Custom $ CallSym \"dhc.system\"\n  -- Our convention:\n  --   [sp] = result ; [sp - 4] = hp_new\n  -- Return (result, #RealWorld).\n  ] ++ if impure then\n      [ Get_global sp  -- hp = [sp - 4]\n      , I32_const 4\n      , I32_sub\n      , I32_load 2 0\n      , Set_global hp\n      , Get_global hp  -- [hp] = TagSum | (2 << 8)\n      , I32_const $ fromIntegral $ fromEnum TagSum + 256 * 2\n      , I32_store 2 0\n      , Get_global hp  -- [hp + 4] = 0\n      , I32_const 0\n      , I32_store 2 4\n      , Get_global hp  -- [hp + 8] = [sp]\n      , Get_global sp\n      , I32_load 2 0\n      , I32_store 2 8\n      , Get_global hp  -- [hp + 12] = 42\n      , I32_const 42\n      , I32_store 2 12\n      , Get_global sp  -- [sp + 8*argCount + 8] = hp\n      , Get_global hp\n      , I32_store 2 $ 8*fromIntegral argCount + 8\n      , Get_global hp  -- hp = hp + 16\n      , I32_const 16\n      , I32_add\n      , Set_global hp\n      , Get_global sp  -- sp = sp + 8*argCount + 4\n      , I32_const $ 8*fromIntegral argCount + 4\n      , I32_add\n      , Set_global sp\n      , End\n      ]\n    else\n      [ Get_global sp  -- hp = [sp - 4]\n      , I32_const 4\n      , I32_sub\n      , I32_load 2 0\n      , Set_global hp\n      -- TODO: Make it lazy with an indirection.\n      , Get_global sp  -- [sp + 8*argCount + 4] = [sp]\n      , Get_global sp\n      , I32_load 2 0\n      , I32_store 2 $ 8*fromIntegral argCount + 4\n      , Get_global sp  -- sp = sp + 8*argCount\n      , I32_const $ 8*fromIntegral argCount\n      , I32_add\n      , Set_global sp\n      , End\n      ]\n"
  },
  {
    "path": "test/example.hs",
    "content": "-- To get this working in GHC, uncomment the following 2 lines:\n--   import Prelude hiding (foldr, uncurry, sum, map, enumFromTo)\n--   putInt = print\n\n-- Gratuitous mutual recursion.\nfactorial n = case n == 0 of True  -> 1\n                             False -> n * factorial2 (n - 1)\nfactorial2 n = case n == 0 of True  -> 1\n                              False -> n * factorial (n - 1)\nfoldr f n xs = case xs of [] -> n\n                          (a:as) -> f a (foldr f n as)\nuncurry f p = case p of (a, b) -> f a b\nsum = foldr (+) 0\nenumFromTo a b = case a > b of True  -> []\n                               False -> a : enumFromTo (a + 1) b\nmap f = foldr ((:) . f) []\ntenTimes x = 10 * x\nf rec n = case n == 0 of True -> 0\n                         False -> rec (n - 1) + 2*n - 1\nmain = do\n  putStr \"recursion with fix: \"\n  let fix f = f $ fix f\n  putInt $ fix f 100\n  putStr \"\\n5! + (10 + 20 + 30 + 40 + 50) = \"\n  putInt $ uncurry (+) (factorial 5, sum $ map tenTimes [1..5])\n  putStr \"\\n\"\n"
  },
  {
    "path": "test/rundhc.hs",
    "content": "import Data.Char\nimport qualified Data.ByteString as B\nimport Hero.Hero\n\nmain :: IO ()\nmain = putStr =<< runDemo =<< B.getContents\n\nrunDemo :: B.ByteString -> IO String\nrunDemo asm = stateVM . snd <$> runWasm \"main\" [] (mkHeroVM \"\" syscall wasm [])\n  where\n  wasm = either error id $ parseWasm asm\n  syscall (\"system\", \"putStr\") vm [I32_const ptr, I32_const len] = pure ([],\n    putStateVM (stateVM vm ++ [chr $ getNumVM 1 (ptr + i) vm | i <- [0..len - 1]]) vm)\n  syscall (\"system\", \"putInt\") vm [I32_const lo, I32_const hi] = pure ([],\n    putStateVM (stateVM vm ++ show (fromIntegral lo + fromIntegral hi * 2^(32 :: Integer) :: Integer)) vm)\n  syscall a _ b = error $ show (\"BUG! bad syscall\", a, b)\n"
  }
]