Repository: dfinity/dhc Branch: master Commit: 60ac6c85ca02 Files: 31 Total size: 195.1 KB Directory structure: gitextract_mf1bhr8r/ ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.asciidoc ├── default.nix ├── dhc/ │ └── Main.hs ├── dhc.cabal ├── other/ │ ├── Demo.hs │ └── dhcdemo.lhs ├── src/ │ ├── Asm.hs │ ├── Ast.hs │ ├── Boost.hs │ ├── DHC.hs │ ├── Encode.hs │ ├── Hero/ │ │ ├── .gitignore │ │ ├── Hero.hs │ │ ├── HeroIO.hs │ │ ├── Parse.hs │ │ ├── README.asciidoc │ │ ├── default.nix │ │ ├── hero.cabal │ │ └── test/ │ │ ├── Main.hs │ │ └── bm.hs │ ├── Parse.hs │ ├── Std.hs │ └── WasmOp.hs └── test/ ├── Main.hs ├── SoloSyscall.hs ├── example.hs └── rundhc.hs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /.stack-work /dist ================================================ FILE: Dockerfile ================================================ FROM ubuntu:xenial ENV DEBIAN_FRONTEND noninteractive ENV LD_LIBRARY_PATH /usr/local/lib ENV PATH ${PATH}:/root/.local/bin RUN apt-get update RUN apt-get install -y asciidoc curl git libbz2-dev libncurses5-dev ### Install Stack RUN mkdir -p /root/.local/bin RUN curl -sSL https://get.haskellstack.org | sh ### Install Haste WORKDIR /tmp RUN git clone https://github.com/valderman/haste-compiler WORKDIR /tmp/haste-compiler RUN git checkout 0.6.0.0 RUN 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 RUN stack setup RUN stack install RUN stack install hsc2hs RUN stack exec haste-boot -- --force --local ### Install Haste package manager WORKDIR /root/.haste/x86_64-linux-haste-0.6.0.0-ghc-7.10.3/haste-cabal RUN cp libgmp.so.3 ${LD_LIBRARY_PATH} RUN cp haste-cabal.bin /root/.local/bin/haste-cabal ### Install Haste packages RUN haste-cabal install bimap parsec ### Create workspace RUN mkdir /workspace WORKDIR /workspace ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: Makefile ================================================ .PHONY: all test clean all: dhcdemo.js dhcdemo.html dhcdemo.js: *.hs dhcdemo.lhs; hastec -Wall dhcdemo.lhs dhcdemo.html: dhcdemo.lhs; asciidoc dhcdemo.lhs test:; ghc -O2 -Wall test/Main.hs && test/Main herotest:; ghc -O2 -Wall Hero/test/Main.hs && Hero/test/Main clean:; rm -rf *.hi *.jsmod *.o *.dyn_hi *.dyn_o ================================================ FILE: README.asciidoc ================================================ = Dfinity Haskell Compiler = DHC is a Haskell compiler that produces WebAssembly. It accepts only a tiny subset of the language. == Live demo == https://dhc.dfinity.org == Installation / Dependencies == Run `nix build`. == Usage / Examples == The `dhc` program takes Haskell source on standard input and compiles it to WebAssembly on standard output. Two IO functions are defined: ------------------------------------------------------------------------------ putStr :: String -> IO () putInt :: Int -> IO () -- `Int` means 64-bit integer. ------------------------------------------------------------------------------ which respectively call WebAssembly imports: ------------------------------------------------------------------------------ system.putStr (ptr : i32, len : i32) system.putInt (lo : i32, hi : i32) ------------------------------------------------------------------------------ In `system.putInt`, we split the integer into 32-bit halves to make life easier for JavaScript. The `rundhc` tool can interpret the output of `dhc`. It expects the input WebAssembly binary to export a function named `main` that takes no arguments and returns no arguments. For example: ------------------------------------------------------------------------------ $ echo 'public(main) main=putStr"Hello, World!\n"' | ./dhc | ./rundhc Hello, World! ------------------------------------------------------------------------------ == License == http://dfinity.network[*(C) 2017 DFINITY STIFTUNG*]. All code and designs are open sourced under GPL V3. image::https://user-images.githubusercontent.com/6457089/32753794-10f4cbc2-c883-11e7-8dcf-ff8088b38f9f.png[dfinity logo] ================================================ FILE: default.nix ================================================ { pkgs ? import {}, compiler ? "ghc822" }: with pkgs; let drv = haskellPackages.callCabal2nix "dhc" ./. {}; in if pkgs.lib.inNixShell then stdenv.lib.overrideDerivation drv.env (oldAttrs : { nativeBuildInputs = oldAttrs.nativeBuildInputs ++ [ cabal-install stack ]; }) else drv ================================================ FILE: dhc/Main.hs ================================================ -- Takes Haskell source given on standard input and compiles it to -- WebAssembly which is dumped to standard output. import qualified Data.ByteString as B import Asm import Demo main :: IO () main = do s <- getContents case hsToWasm jsDemoBoost s of Left err -> error err Right bin -> B.putStr $ B.pack $ fromIntegral <$> bin ================================================ FILE: dhc.cabal ================================================ name: dhc version: 0.1.0 synopsis: A Haskell compiler that produces WebAssembly. license: GPL-3 copyright: 2017 DFINITY Stiftung. category: Language homepage: https://github.com/dfinity/dhc bug-reports: https://github.com/dfinity/dhc/issues build-type: Simple cabal-version: >=1.10 library build-depends: base, binary, bytestring, containers, mtl, parsec default-language: Haskell2010 hs-source-dirs: src exposed-modules: Asm Ast Boost DHC Encode Hero.Hero Hero.HeroIO Hero.Parse Parse Std WasmOp ghc-options: -O2 -Wall executable dhc default-language: Haskell2010 hs-source-dirs: dhc other main-is: Main.hs other-modules: Demo build-depends: base, binary, bytestring, containers, dhc, mtl, parsec ghc-options: -O2 -Wall -threaded test-suite test default-language: Haskell2010 type: exitcode-stdio-1.0 hs-source-dirs: test other main-is: Main.hs build-depends: base, binary, bytestring, containers, dhc, heredoc, HUnit, mtl, parsec other-modules: Demo SoloSyscall ================================================ FILE: other/Demo.hs ================================================ -- DHC Boost that provides 2 functions: -- -- putStr :: String -> IO () -- putInt :: Int -> IO () -- -- and expects the host to provide 2 syscalls: -- -- system.putStr (pointer : I32, length : I32) -> () -- system.putInt (n : I64) -> () -- -- The JavaScript edition expects a variant of system.putInt: -- -- system.putInt (lo : I32, hi : I32) -> () module Demo (demoBoost, jsDemoBoost) where import Ast import Boost import WasmOp sp :: Int sp = 0 demoBoost :: Boost demoBoost = Boost [ (("system", "putStr"), ([I32, I32], [])) , (("system", "putInt"), ([I64], [])) ] [] [ ("putStr", (TC "String" :-> io (TC "()"), putStrAsm)) , ("putInt", (TC "Int" :-> io (TC "()"), [ Custom $ ReduceArgs 1 , Get_global sp -- system.putInt [[sp + 4] + 8].64 , I32_load 2 4 , I64_load 3 8 , Custom $ CallSym "system.putInt" , Get_global sp -- sp = sp + 12 , I32_const 12 , I32_add , Set_global sp , Custom $ CallSym "#nil42" , End ])) ] [] where io = TApp (TC "IO") -- The JavaScript edition of the host splits an int64 into low and high 32-bit -- words, since current JavaScript engines lack support for 64-bit integers. jsDemoBoost :: Boost jsDemoBoost = Boost [ (("system", "putStr"), ([I32, I32], [])) , (("system", "putInt"), ([I32, I32], [])) ] [] [ ("putStr", (TC "String" :-> io (TC "()"), putStrAsm)) , ("putInt", (TC "Int" :-> io (TC "()"), [ Custom $ ReduceArgs 1 , Get_global sp -- system.putInt [[sp + 4] + 8] [[sp + 4] + 12] , I32_load 2 4 , I32_load 2 8 , Get_global sp , I32_load 2 4 , I32_load 2 12 , Custom $ CallSym "system.putInt" , Get_global sp -- sp = sp + 12 , I32_const 12 , I32_add , Set_global sp , Custom $ CallSym "#nil42" , End ])) ] [] where io = TApp (TC "IO") putStrAsm :: [QuasiWasm] putStrAsm = [ Custom $ ReduceArgs 1 , Get_global sp -- system.putStr ([[sp + 4] + 4] [[sp + 4] + 8]) [[sp + 4] + 12] , I32_load 2 4 , I32_load 2 4 , Get_global sp , I32_load 2 4 , I32_load 2 8 , I32_add , Get_global sp , I32_load 2 4 , I32_load 2 12 , Custom $ CallSym "system.putStr" , Get_global sp -- sp = sp + 12 , I32_const 12 , I32_add , Set_global sp , Custom $ CallSym "#nil42" , End ] ================================================ FILE: other/dhcdemo.lhs ================================================ = DHC Demo = The following compiles Haskell to WebAssembly and runs it. Only a tiny fragment of the language is supported. There is almost no syntax sugar. System calls: ------------------------------------------------------------------------------ putStr :: String -> IO () putInt :: Int -> IO () ------------------------------------------------------------------------------ There is no garbage collection. https://github.com/dfinity/dhc[Source]. [pass] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//////////////////////////////////////////////////////////////////////////////
\begin{code}
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Data.Char
import Haste.DOM
import Haste.Events
import Haste.Foreign
import Asm
import Demo

append :: Elem -> String -> IO ()
append e s = do
  v <- getProp e "innerHTML"
  setProp e "innerHTML" $ v ++ s

sysPutStr :: Elem -> Int -> Int -> IO ()
sysPutStr e a n = append e =<< mapM (fmap chr . load8 . (a +)) [0..n - 1]
  where load8 = ffi "load8" :: Int -> IO Int

sysPutInt :: Elem -> Int -> Int -> IO ()
sysPutInt e y x = append e $ case x of
  0 -> show y ++ if y >= 0 then "" else
    " (unsigned = " ++ show (fromIntegral y + b) ++ ")"
  _ -> show $ fromIntegral x * b + ((fromIntegral y + b) `mod` b)
  where b = 2^(32 :: Int) :: Integer

main :: IO ()
main = withElems ["src", "asm", "go", "get", "out"] $ \[src, asmEl, goB, getB, outE] -> do
  export "sysPutStr" $ sysPutStr outE
  export "sysPutInt" $ sysPutInt outE
  let
    go f = do
      setProp asmEl "value" ""
      s <- ("public (main)\n" ++) <$> getProp src "value"
      case hsToWasm jsDemoBoost s of
        Left err -> setProp asmEl "value" err
        Right asm -> do
          setProp asmEl "value" $ show asm
          f asm
  void $ goB `onEvent` Click $ const $ go $ ffi "runWasmInts"
  void $ getB `onEvent` Click $ const $ go $ ffi "downloadWasm"

\end{code}
//////////////////////////////////////////////////////////////////////////////


================================================
FILE: src/Asm.hs
================================================
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
#ifdef __HASTE__
{-# LANGUAGE PackageImports #-}
#endif
module Asm
  ( hsToWasm
  , Ins(..)
  , WasmType(..)  -- Re-export from WasmOp.
  , hsToIns
  , hsToGMachine
  , tpGlobalIndex
  ) where

import Control.Arrow
#ifdef __HASTE__
import "mtl" Control.Monad.State
import Data.Map.Strict (Map)
#else
import Control.Monad.State
import Data.ByteString.Short (ShortByteString, unpack)
import qualified Data.ByteString.Short as SBS
import Data.Map.Strict (Map, restrictKeys)
import Data.Semigroup ()
#endif
import Data.Bits
import Data.Char
import Data.Int
import Data.List
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as S

import Boost
import DHC
import Encode
import Std
import WasmOp

import System.IO.Unsafe (unsafePerformIO)

#ifdef __HASTE__
sbslen :: String -> Int
sbslen = length
unpack :: String -> [Int]
unpack = fmap ord
type ShortByteString = String
restrictKeys :: Ord k => Map k a -> Set k -> Map k a
restrictKeys m s = M.filterWithKey (\k _ -> S.member k s) m
#else
sbslen :: ShortByteString -> Int
sbslen = SBS.length
#endif

-- | G-Machine instructions.
data Ins = Copro Int Int | PushInt Int64 | Push Int | PushGlobal String
  | PushRef Int32
  | PushString ShortByteString
  | MkAp | Slide Int | Split Int | Eval
  | UpdatePopEval Int | UpdateInd Int | Alloc Int
  | Casejump [(Maybe Int, [Ins])] | Trap
  | PushCallIndirect [Type]
  | WasmPush [Ins] Type
  | WasmCallIndirect [Type]
  deriving Show

nPages :: Int
nPages = 8

data WasmMeta = WasmMeta
  -- Arity of each user-defined function, whether exported or not.
  -- Eval uses this to remove the spine correctly.
  { arities :: Map String Int
  -- Public and private functions that can become references.
  -- We also hang on to the type of each argument as well as a function
  -- to decode it from a heap object.
  , exports :: [(String, [(Type, [Ins])])]
  , elements :: [(String, [(Type, [Ins])])]
  , callTypes :: [[Type]]  -- Types needed by call_indirect ops.
  , strEndHP :: Int  -- Heap address immediately past the string constants.
  , strAddrs :: Map ShortByteString Int  -- String constant addresses.
  , storeTypes :: [Type]  -- Global store types.
  , callEncoders :: Map String [Ins]  -- Helpers for call_indirect that encode messages.
  }

hsToGMachine :: Boost -> String -> Either String (Map String Int, Map String [Ins])
hsToGMachine boost hs = first arities <$> hsToIns boost hs

hsToWasm :: Boost -> String -> Either String [Int]
hsToWasm boost s = insToBin s b . astToIns <$> hsToAst b qq s where
  b = stdBoost <> boost
  qq "here" h = Right h
  qq "wasmFromFile" fileName = do
    let prog = unsafePerformIO (readFile fileName)
    case hsToWasm boost prog of
        Left err -> Left err
        Right ints -> Right $ chr <$> ints
  qq "wasm" prog = case hsToWasm boost prog of
    Left err -> Left err
    Right ints -> Right $ chr <$> ints
  qq scheme _ = Left $ "hsToWasm: bad scheme: " ++ scheme

hsToIns :: Boost -> String -> Either String (WasmMeta, Map String [Ins])
hsToIns boost s = astToIns <$> hsToAst (stdBoost <> boost) qq s where
  qq "here" h = Right h
  qq scheme _ = Left $ "hsToIns: bad scheme: " ++ scheme

data CompilerState = CompilerState
  -- Bindings are local. They start empty and finish empty.
  -- During compilation, they hold the stack position of the bound variables.
  { bindings :: [(String, Int)]
  -- Each call_indirect indexes into the type section of the binary.
  -- We record the types used by the binary so we can collect and look them
  -- up when generating assembly.
  -- TODO: It'd be better to fold over CompilerState during compile to
  -- incrementally update these fields.
  , callIndirectTypes :: [[Type]]
  , stringConstants :: [ShortByteString]
  -- Compilation may generate auxiliary helpers.
  , helpers :: [(String, [Ins])]
  }

align4 :: Int -> Int
align4 n = (n + 3) `div` 4 * 4

mkStrConsts :: [ShortByteString] -> (Int, Map ShortByteString Int)
mkStrConsts = f (0, []) where
  f (p, ds) [] = (p, M.fromList ds)
  f (k, ds) (s:rest) = f (k + 16 + align4 (sbslen s), (s, k):ds) rest

astToIns :: Clay -> (WasmMeta, Map String [Ins])
astToIns cl = (WasmMeta
  { arities = funs
  , exports = compileDecoders <$> publics cl
  , elements = compileDecoders <$> secrets cl
  , callTypes = ciTypes
  , strEndHP = hp1
  , strAddrs = addrs
  , storeTypes = snd <$> stores cl
  , callEncoders = M.fromList $ concatMap helpers cs
  }, fst <$> compilerOut) where
  compilerOut = compile (fst <$> stores cl) <$> supers cl
  cs = snd <$> M.elems compilerOut
  ciTypes = foldl' union [] $ callIndirectTypes <$> cs
  (hp1, addrs) = mkStrConsts $ nub $ concatMap stringConstants cs
  funs = M.union ((\(Ast (Lam as _)) -> length as) <$> supers cl) $
    M.fromList $ concatMap (\n -> [("#set-" ++ show n, 1), ("#get-" ++ show n, 0)]) [0..length (stores cl) - 1]
  -- Argument decoders only use a certain subset of functions.
  compileDecoders = second $ fmap $ second (fst . compile [])

toDfnType :: Type -> WasmType
toDfnType t = case t of
  TApp (TC "()") _ -> Ref "Elem"
  TApp (TC "[]") _ -> Ref "Elem"
  TC "()" -> Ref "Elem"
  TC "Int" -> I64
  TC "I32" -> I32
  TC "Bool" -> I32
  TC "String" -> Ref "Databuf"
  TC s | elem s ["Port", "Databuf", "Actor", "Module"] -> Ref s
  _ -> error $ "BUG! type check failed to catch: " ++ show t

followGCalls :: [String] -> Set String -> Map String [Ins] -> Set String
followGCalls fs prims m = execState (go fs) $ S.fromList fs where
  go (f:rest) = if S.member f prims
    then modify $ S.insert f
    else do
      maybe (pure ()) tr $ M.lookup f m
      go rest
  go [] = pure ()
  tr (w:rest) = do
    case w of
      PushGlobal v -> do
        s <- get
        when (S.notMember v s) $ do
          put $ S.insert v s
          go [v]
      PushCallIndirect ty -> go [show ty]
      WasmPush enc _ -> tr enc
      Casejump alts -> mapM_ tr $ snd <$> alts
      _ -> pure ()
    tr rest
  tr [] = pure ()

-- | Join two i32s into a single i64.
mk64 :: Int -> Int -> Int64
mk64 a b = fromIntegral a + shift (fromIntegral b) 32

insToBin :: String -> Boost -> (WasmMeta, Map String [Ins]) -> [Int]
insToBin src boost@(Boost imps _ _ boostFuns) (wm@WasmMeta {exports, elements, strAddrs, storeTypes}, gmachine) = wasm where
  wasm = encodeWasm ProtoWasm
    { sectImports = imps
    , sectFunctions = snd <$> wasmFuns
    , tableSize = 256
    , sectGlobals =  -- Global section (1 = mutable).
      [ [encType I32, 1, 0x41] ++ sleb128 memTop ++ [0xb]  -- SP
      , [encType I32, 1, 0x41] ++ sleb128 (strEndHP wm) ++ [0xb]  -- HP
      , [encType I32, 1, 0x41, 0, 0xb]  -- BP
      , [encType I32, 1, 0x41] ++ sleb128 (length ees) ++ [0xb]  -- TP
      ]
      -- Global stores.
      -- First one records if `main` has been run yet.
      ++ map declareGlobal (TC "I32":storeTypes)
    , sectExports = [(s, wasmFunNo ('@':s)) | (s, _) <- exports]
    , sectElements = [(0, wasmFunNo . ('@':) . fst <$> ees)]
    , sectDfn = ((wasmFunNo . ('@':)) *** map (toDfnType . fst)) <$> ees
    , sectPersist = zip [mainCalled..] $ toDfnType <$> TC "I32":storeTypes
    , sectsGeneric =
      [ (5, [0 : leb128 nPages])  -- Memory section (0 = no-maximum).
      , (11, encStrConsts <$> M.assocs strAddrs)  -- Data section.
      ]
    , sectsCustom =
      [ ("dfndbg", [ord <$> show (sort $ swp <$> M.assocs wasmFunMap)])
      , ("dfnhs", [ord <$> src])
      ]
    }
  ees = exports ++ elements
  declareGlobal (TC "Int") = [encType I64, 1, 0x42, 0, 0xb]
  declareGlobal _ = [encType I32, 1, 0x41, 0, 0xb]
  swp (a, b) = (b, a)
  memTop = 65536*nPages - 4
  encStrConsts (s, offset) = concat
    [ [0, 0x41] ++ sleb128 offset ++ [0xb]
    , leb128 $ 16 + sbslen s
    , [fromEnum TagString, 0, 0, 0]
    , enc32 $ offset + 16
    , enc32 0
    , enc32 $ sbslen s
    , fromIntegral <$> unpack s
    ]
  -- Returns arity and 0-indexed number of given global function.
  getGlobal s = case M.lookup s $ M.insert "main" 0 $ arities wm of
    Just arity -> (arity, wasmFunNo s - firstPrim)
    Nothing -> (arityFromType $ fromMaybe (error $ "BUG! bad global: " ++ s) $ M.lookup s primsType, wasmFunNo s - firstPrim)
  firstPrim = wasmFunNo $ fst $ head evalFuns
  cdq = concatMap deQuasi
  internalFuns =
    [ ("#eval", (([], []), evalAsm))
    , ("#mkap", (([], []), mkApAsm))
    , ("#push32", (([I32], []), push32Asm))  -- Low-level push.
    , ("#pushint", (([I64], []), cdq pushIntAsm))
    , ("#pushref", (([I32], []), cdq pushRefAsm))
    , ("#pushglobal", (([I64], []), cdq pushGlobalAsm))
    , ("#updatepopeval", (([I32], []), cdq updatePopEvalAsm))
    , ("#updateind", (([I32], []), updateIndAsm))
    , ("#alloc", (([I32], []), cdq allocAsm))
    , ("#pairwith42", (([I32], []), pairWith42Asm))
    , ("#nil42", (([], []), cdq nil42Asm))
    ] ++ (second (second cdq) <$> boostFuns)
  noInOut = ([], []) :: ([WasmType], [WasmType])
  wasmFuns :: [(String, WasmFun)]
  wasmFuns =
    (second (\((ins, outs), a) -> WasmFun (ins, outs) [] a) <$> internalFuns)
    ++ evalFuns
    -- Wrappers for functions in "public" and "secret" section.
    ++ (wrap <$> ees)
  evalFuns = concat  -- Functions that "#eval" can call.
    -- Primitive functions.
    -- The assembly for "#eval" requires that the primitive functions
    -- directly precede those defined in the program.
    [ M.assocs $ WasmFun noInOut [] . cdq . snd <$> livePrims
    -- Global get and set functions that interact with the DHC stack.
    , concat (zipWith mkStoreAsm storeTypes [0..])
    -- Functions from the program, except `main`.
    , M.assocs $ fromGMachine <$> M.delete "main" liveGs
    -- The `main` function. Any supplied `main` function is appended to
    -- some standard setup code.
    , [("main", WasmFun noInOut [] $ preMainAsm ++ concatMap fromIns (fromMaybe [] $ M.lookup "main" liveGs) ++ [End])]
    -- Wrappers for call_indirect ops.
    , M.assocs $ WasmFun noInOut [] . (++ [End]) . concatMap fromIns <$> callEncoders wm
    ]

  -- The "***" is a hack to force it to follow the instructions for all
  -- argument encoders and decoders.
  liveGIds = followGCalls ("***":"main":(fst <$> ees)) (M.keysSet prims) $ gmachine `M.union` M.singleton "***" (concatMap snd (concatMap snd ees) ++ concat (M.elems $ callEncoders wm))
  liveGs = restrictKeys gmachine liveGIds
  livePrims = restrictKeys prims liveGIds

  fromGMachine g = WasmFun noInOut [] $ (++ [End]) $ concatMap fromIns g
  preMainAsm =
    [ I32_const 1  -- mainCalled = 1
    , Set_global mainCalled
    ]
  wasmFunMap = M.fromList $ zip (((\(m, f) -> m ++ "." ++ f) . fst <$> imps) ++ (fst <$> wasmFuns)) [0..]
  wasmFunNo s = fromMaybe (error s) $ M.lookup s wasmFunMap

  wrap (f, ps) = let (inTypes, decoders) = unzip ps in
    (,) ('@':f) $ WasmFun (toWasmType <$> inTypes, []) [] $
    -- Wraps a DHC function.
    -- When a wasm function f(arg0, arg1, ...) is called,
    -- the arguments are placed in local variables.
    -- This wrapper builds:
    --
    --   f :@ arg0 :@ arg 1 :@ ... :@ #RealWorld
    --
    -- on the heap, places a pointer to this on the stack, then calls Eval.
    --
    -- Additionally, for each non-`main` function, first call `main`
    -- if a certain global flag is false.
    -- The `main` function always exists and sets this global flag.
    (if f /= "main" then
    [ Get_global mainCalled  -- if (!mainCalled) mainCalled = 1, main;
    , I32_eqz
    , If Nada (
      [ I32_const $ fromIntegral memTop  -- sp = top of memory
      , Set_global sp
      , I32_const 42  -- #push32 42
      , Call $ wasmFunNo "#push32"
      ] ++ concatMap fromIns [PushGlobal "main", MkAp, Eval]) []
    ]
    else []) ++

    [ I32_const $ fromIntegral memTop  -- sp = top of memory
    , Set_global sp
    , I32_const 42  -- #push32 42
    , Call $ wasmFunNo "#push32"
    ] ++
    -- Input arguments are local variables.
    -- We move these to our stack in reverse order.
    concat (reverse $ zipWith3 fromWire inTypes decoders [0..]) ++
    -- Build the spine.
    concatMap fromIns (PushGlobal f : replicate (length inTypes + 1) MkAp) ++
    [ Call $ wasmFunNo "#eval"
    , End
    ]
  fromWire t dec i =
    [ Get_local i
    , case toWasmType t of
      I64 -> Call $ wasmFunNo "#pushint"
      _   -> Call $ wasmFunNo "#pushref"
    ] ++ concatMap fromIns dec ++
    [ Call $ wasmFunNo "#mkap" ]
  evalAsm =
    [ Block Nada
      [ Loop Nada
        [ Get_global sp  -- bp = [sp + 4]
        , I32_load 2 4
        , Set_global bp
        , Block Nada
          [ Block Nada
            [ Get_global bp
            , I32_load8_u 0 0
            , Br_table [0, 1, 3] 4  -- case [bp].8u; branch on Tag
            ]  -- 0: Ap
          , Get_global bp  -- #push32 [bp + 8]
          , I32_load 2 8
          , Call $ wasmFunNo "#push32"
          , Br 1
          ]  -- 1: Ind.
        , Get_global sp  -- [sp + 4] = [bp + 4]
        , Get_global bp
        , I32_load 2 4
        , I32_store 2 4
        , Br 0
        ]  -- 2: Eval loop.
      ]  -- 3: Global
    , Get_global bp  -- save bp, sp
    , Get_global sp
    , Get_global sp  -- bp = sp + 4 + 4 * ([bp].16u >> 8)
    , I32_const 4
    , I32_add
    , Get_global bp
    , I32_load16_u 1 0
    , I32_const 8
    , I32_shr_u
    , I32_const 4
    , I32_mul
    , I32_add
    , Set_global bp

    , Loop Nada  -- Remove spine.
      [ Get_global sp  -- sp = sp + 4
      , I32_const 4
      , I32_add
      , Set_global sp
      , Get_global sp  -- if sp /= bp then
      , Get_global bp
      , I32_ne
      , If Nada
        [ Get_global sp  -- [sp] = [[sp + 4] + 12]
        , Get_global sp
        , I32_load 2 4
        , I32_load 2 12
        , I32_store 2 0
        , Br 1
        ] []  -- If
      ]  -- Loop
    , Set_global sp  -- restore bp, sp
    , Set_global bp
    ] ++ nest n ++ [End]
    where
      -- Eval functions are resolved in a giant `br_table`. This is ugly, but
      -- avoids run-time type-checking.
      n = length evalFuns
      nest 0 =
        [ Get_global bp  -- case [bp + 4]
        , I32_load 2 4
        , Br_table [0..n-1] n
        ]
      nest k = [Block Nada $ nest $ k - 1, Call $ firstPrim + k - 1, Return]

  mkStoreAsm :: Type -> Int -> [(String, WasmFun)]
  mkStoreAsm t n =
    [ ("#set-" ++ show n, WasmFun noInOut [] $
      [ Get_global sp  -- Push 0, Eval.
      , I32_load 2 4
      , Call $ wasmFunNo "#push32"
      , Call $ wasmFunNo "#eval"
      ] ++ (case t of
        TC "Int" ->
          [ Get_global sp  -- Set_global n [[sp + 4] + 8].64
          , I32_load 2 4
          , I64_load 3 8
          , Set_global $ storeOffset + n
          ]
        _ ->
          [ Get_global sp  -- Set_global n [[sp + 4] + 4]
          , I32_load 2 4
          , I32_load 2 4
          , Set_global $ storeOffset + n
          ]
      ) ++
      [ Get_global sp  -- sp = sp + 12
      , I32_const 12
      , I32_add
      , Set_global sp
      , Call $ wasmFunNo "#nil42"
      , End
      ])
    , ("#get-" ++ show n, WasmFun noInOut [] $
      [ Get_global hp  -- PUSH hp
      ] ++ (case t of
        TC "Int" ->
          [ Get_global hp  -- [hp] = TagInt
          , tag_const TagInt
          , I32_store 2 0
          , Get_global hp  -- [hp + 8] = Get_global n
          , Get_global $ storeOffset + n
          , I64_store 3 8
          , Get_global hp  -- hp = hp + 16
          , I32_const 16
          , I32_add
          , Set_global hp
          ]
        _ ->
          [ Get_global hp  -- [hp] = TagRef
          , tag_const TagRef
          , I32_store 2 0
          , Get_global hp  -- [hp + 4] = Get_global n
          , Get_global $ storeOffset + n
          , I32_store 2 4
          , Get_global hp  -- hp = hp + 8
          , I32_const 8
          , I32_add
          , Set_global hp
          ]
      ) ++
      [ Get_global sp  -- sp = sp + 4
      , I32_const 4
      , I32_add
      , Set_global sp
      , Call $ wasmFunNo "#pairwith42"
      , End
      ])
    ]
  deQuasi :: QuasiWasm -> [WasmOp]
  deQuasi (Custom x) = case x of
    CallSym s -> [Call $ wasmFunNo s]
    ReduceArgs n -> concat $ replicate n $ concatMap fromIns [Push (n - 1), Eval]

  deQuasi (Block t body) = [Block t $ cdq body]
  deQuasi (Loop  t body) = [Loop  t $ cdq body]
  deQuasi (If    t a b)  = [If    t (cdq a) $ cdq b]
  deQuasi op = [error "missing deQuasi case?" <$> op]

  prims = M.fromList $ boostPrims boost
  primsType = fst <$> prims

  fromIns :: Ins -> [WasmOp]
  fromIns instruction = case instruction of
    Trap -> [ Unreachable ]
    Eval -> [ Call $ wasmFunNo "#eval" ]  -- (Tail call.)
    PushInt n -> [ I64_const n, Call $ wasmFunNo "#pushint" ]
    PushRef n -> [ I32_const n, Call $ wasmFunNo "#pushref" ]
    Push n ->
      [ Get_global sp
      , I32_load 2 $ fromIntegral $ 4*(n + 1)
      , Call $ wasmFunNo "#push32"
      ]
    MkAp -> [ Call $ wasmFunNo "#mkap" ]
    PushGlobal fun | (n, g) <- getGlobal fun ->
      [ I64_const $ mk64 (fromEnum TagGlobal + shift n 8) g
      , Call $ wasmFunNo "#pushglobal"
      ]
    PushString s ->
      -- #push32 (address of string const)
      [ I32_const $ fromIntegral $ strAddrs M.! s
      , Call $ wasmFunNo "#push32"
      ]
    PushCallIndirect ty ->
      -- 3 arguments: slot, argument tuple, #RealWorld.
      [ I64_const $ mk64 (fromEnum TagGlobal + shift 3 8) $ wasmFunNo (show ty) - firstPrim
      , Call $ wasmFunNo "#pushglobal"
      ]
    Slide 0 -> []
    Slide n ->
      [ Get_global sp  -- [sp + 4*(n + 1)] = [sp + 4]
      , Get_global sp
      , I32_load 2 4
      , I32_store 2 $ 4*(fromIntegral n + 1)
      , Get_global sp  -- sp = sp + 4*n
      , I32_const $ 4*fromIntegral n
      , I32_add
      , Set_global sp
      ]
    Alloc n -> [ I32_const $ fromIntegral n, Call $ wasmFunNo "#alloc" ]
    UpdateInd n ->
      [ I32_const $ fromIntegral $ 4*(n + 1), Call $ wasmFunNo "#updateind" ]
    UpdatePopEval n ->
      [ I32_const $ fromIntegral $ 4*(n + 1)
      , Call $ wasmFunNo "#updatepopeval"
      ]
    Copro m n ->
      [ Get_global hp  -- [hp] = (TagSum | (n << 8) | (m << 32)).64
      , I64_const $ mk64 (fromEnum TagSum + shift n 8) m
      , I64_store 3 0
      ] ++ concat [
        [ Get_global hp  -- [hp + 4 + 4*i] = [sp + 4*i]
        , Get_global sp
        , I32_load 2 $ fromIntegral $ 4*i
        , I32_store 2 $ fromIntegral $ 4 + 4*i
        ] | i <- [1..n]] ++
      [ Get_global sp  -- sp = sp + 4*n
      , I32_const $ fromIntegral $ 4*n - 4
      , I32_add
      , Set_global sp
      , Get_global sp  -- [sp + 4] = hp
      , Get_global hp
      , I32_store 2 4
      , Get_global hp  -- hp = hp + 8 + ceil(n / 2) * 8
      , I32_const $ fromIntegral $ 8 + 8 * ((n + 1) `div` 2)
      , I32_add
      , Set_global hp
      ]
    Casejump alts0 -> let
      (underscore, unsortedAlts) = partition (isNothing . fst) alts0
      alts = sortOn fst unsortedAlts
      catchall = if null underscore then [Trap] else snd $ head underscore
      tab = zip (fromJust . fst <$> alts) [0..]
      m = maximum $ fromJust . fst <$> alts
      nest j (ins:rest) = pure $ Block Nada $ nest (j + 1) rest ++ concatMap fromIns ins ++ [Br j]
      nest _ [] = pure $ Block Nada
        [ Get_global bp  -- Br_table [bp + 4]
        , I32_load 2 4
        , Br_table [fromIntegral $ fromMaybe (length alts) $ lookup i tab | i <- [0..m]] $ m + 1
        ]
      in if null alts then concatMap fromIns catchall else
      -- [sp + 4] should be:
      -- 0: TagSum
      -- 4: "Enum"
      -- 8, 12, ...: fields
      [ Get_global sp  -- bp = [sp + 4]
      , I32_load 2 4
      , Set_global bp
      , Block Nada $ nest 1 (reverse $ snd <$> alts) ++ concatMap fromIns catchall
      ]

    Split 0 -> [Get_global sp, I32_const 4, I32_add, Set_global sp]
    Split n ->
      [ Get_global sp  -- bp = [sp + 4]
      , I32_load 2 4
      , Set_global bp
      , Get_global sp  -- sp = sp - 4*(n - 1)
      , I32_const $ fromIntegral $ 4*(n - 1)
      , I32_sub
      , Set_global sp
      ] ++ concat [
        [ Get_global sp  -- [sp + 4*i] = [bp + 4 + 4*i]
        , Get_global bp
        , I32_load 2 $ fromIntegral $ 4 + 4*i
        , I32_store 2 $ fromIntegral $ 4*i
        ] | i <- [1..n]]
    WasmPush encoder (TC "Int") ->
      concatMap fromIns (encoder ++ [MkAp, Eval]) ++
      [ Get_global sp  -- PUSH [[sp + 4] + 8].64
      , I32_load 2 4
      , I64_load 3 8
      , Get_global sp  -- sp = sp + 4
      , I32_const 4
      , I32_add
      , Set_global sp
      ]
    WasmPush encoder _ ->
      concatMap fromIns (encoder ++ [MkAp, Eval]) ++
      [ Get_global sp  -- PUSH [[sp + 4] + 4]
      , I32_load 2 4
      , I32_load 2 4
      , Get_global sp  -- sp = sp + 4
      , I32_const 4
      , I32_add
      , Set_global sp
      ]
    WasmCallIndirect inTypes ->
      -- 3 arguments: slot, argument tuple, #RealWorld.
      -- Assumes all message arguments have already been pushed.
      [ Get_global sp  -- PUSH [[sp + 4] + 4]
      , I32_load 2 4
      , I32_load 2 4
      , Call_indirect (toWasmType <$> inTypes, [])
      , Get_global sp  -- sp = sp + 16
      , I32_const 16
      , I32_add
      , Set_global sp
      , Call $ wasmFunNo "#nil42"
      ]

sp, hp, bp, tpGlobalIndex, mainCalled, storeOffset :: Int
[sp, hp, bp, tpGlobalIndex, mainCalled, storeOffset] = [0..5]

compile :: [String] -> Ast -> ([Ins], CompilerState)
compile ps d = runState (mk1 ps d) $ CompilerState [] [] [] []

mk1 :: [String] -> Ast -> State CompilerState [Ins]
mk1 pglobals (Ast ast) = case ast of
  -- Thanks to lambda lifting, `Lam` can only occur at the top level.
  Lam as b -> do
    putBindings $ zip as [0..]
    (++ [UpdatePopEval $ length as]) <$> rec b
  I n -> pure [PushInt n]
  S s -> do
    st <- get
    put st { stringConstants = s:stringConstants st }
    pure [PushString s]
  t :@ u -> do
    mu <- rec u
    bump 1
    mt <- rec t
    bump (-1)
    pure $ case last mt of
      Copro _ _ -> mu ++ mt
      _ -> concat [mu, mt, [MkAp]]
  CallSlot ty encoders -> do
    st <- get
    put st { callIndirectTypes = callIndirectTypes st `union` [ty] }
    ms <- forM encoders rec
    addHelper ty ms
    pure [PushCallIndirect ty]
  Var v -> do
    m <- getBindings
    pure $ case lookup v m of
      Just k -> [Push k]
      _ | Just i <- elemIndex v pglobals ->
        -- Stores become (set n, get n) tuples.
        [ PushGlobal $ "#get-" ++ show i
        , PushGlobal $ "#set-" ++ show i
        , Copro 0 2
        ]
      _ -> [PushGlobal v]
  Pack n m -> pure [Copro n m]
  Cas expr alts -> do
    me <- rec expr
    xs <- forM alts $ \(p, body) -> do
      orig <- getBindings
      (f, b) <- case fromApList p of
        (Ast (Pack n _):vs) -> do
          bump $ length vs
          modifyBindings (zip (map (\(Ast (Var v)) -> v) vs) [0..] ++)
          bod <- rec body
          pure (Just $ fromIntegral n, Split (length vs) : bod ++ [Slide (length vs)])
        [Ast (Var s)] -> do
          bump 1
          modifyBindings ((s, 0):)
          (,) Nothing . (++ [Slide 1]) <$> rec body
        _ -> undefined
      putBindings orig
      pure (f, b)
    pure $ me ++ [Eval, Casejump xs]
  Let ds body -> let n = length ds in do
    orig <- getBindings
    bump n
    modifyBindings (zip (fst <$> ds) [n-1,n-2..0] ++)
    dsAsm <- mapM rec $ snd <$> ds
    b <- rec body
    putBindings orig
    pure $ Alloc n : concat (zipWith (++) dsAsm (pure . UpdateInd <$> [n-1,n-2..0])) ++ b ++ [Slide n]
  DictIndex n -> pure [PushRef $ fromIntegral $ 4*n + 8, PushGlobal "#rundict", MkAp]
  _ -> error $ "TODO: compile: " ++ show ast
  where
    bump n = modifyBindings $ fmap $ second (+n)
    modifyBindings f = putBindings =<< f <$> getBindings
    getBindings = gets bindings
    putBindings b = do
      st <- get
      put st { bindings = b }
    rec = mk1 pglobals

fromApList :: Ast -> [Ast]
fromApList (Ast (a :@ b)) = fromApList a ++ [b]
fromApList a = [a]

mkApAsm :: [WasmOp]
mkApAsm =
  [ Get_global hp  -- [hp] = TagAp
  , tag_const TagAp
  , I32_store 2 0
  , Get_global hp  -- [hp + 8] = [sp + 4]
  , Get_global sp
  , I32_load 2 4
  , I32_store 2 8
  , Get_global hp  -- [hp + 12] = [sp + 8]
  , Get_global sp
  , I32_load 2 8
  , I32_store 2 12
  , Get_global sp  -- [sp + 8] = hp
  , Get_global hp
  , I32_store 2 8
  , Get_global sp  -- sp = sp + 4
  , I32_const 4
  , I32_add
  , Set_global sp
  , Get_global hp  -- hp = hp + 16
  , I32_const 16
  , I32_add
  , Set_global hp
  , End
  ]
push32Asm :: [WasmOp]
push32Asm =
  [ Get_global sp  -- [sp] = local_0
  , Get_local 0
  , I32_store 2 0
  , Get_global sp  -- sp = sp - 4
  , I32_const 4
  , I32_sub
  , Set_global sp
  , End
  ]
pushIntAsm :: [QuasiWasm]
pushIntAsm =
  [ Get_global hp  -- #push32 hp
  , Custom $ CallSym "#push32"
  , Get_global hp  -- [hp] = TagInt
  , tag_const TagInt
  , I32_store 2 0
  , Get_global hp  -- [hp + 8] = local_0
  , Get_local 0
  , I64_store 3 8
  , Get_global hp  -- hp = hp + 16
  , I32_const 16
  , I32_add
  , Set_global hp
  , End
  ]
pushRefAsm :: [QuasiWasm]
pushRefAsm =
  [ Get_global hp  -- #push32 hp
  , Custom $ CallSym "#push32"
  , Get_global hp  -- [hp] = TagRef
  , tag_const TagRef
  , I32_store 2 0
  , Get_global hp  -- [hp + 4] = local_0
  , Get_local 0
  , I32_store 2 4
  , Get_global hp  -- hp = hp + 8
  , I32_const 8
  , I32_add
  , Set_global hp
  , End
  ]
pushGlobalAsm :: [QuasiWasm]
pushGlobalAsm =
  [ Get_global hp  -- #push32 hp
  , Custom $ CallSym "#push32"
  , Get_global hp  -- [hp] = local_0.64  -- TagGlobal | (n << 8) | (funNo << 32)
  , Get_local 0
  , I64_store 3 0
  , Get_global hp  -- hp = hp + 8
  , I32_const 8
  , I32_add
  , Set_global hp
  , End
  ]
updatePopEvalAsm :: [QuasiWasm]
updatePopEvalAsm =
  [ Get_global sp  -- bp = [sp + 4]
  , I32_load 2 4
  , Set_global bp
  , Get_global sp  -- sp = sp + local_0
  , Get_local 0  -- Should be 4*(n + 1).
  , I32_add
  , Set_global sp
  , Get_global sp  -- [[sp + 4]] = Ind
  , I32_load 2 4
  , tag_const TagInd
  , I32_store 2 0
  , Get_global sp  -- [[sp + 4] + 4] = bp
  , I32_load 2 4
  , Get_global bp
  , I32_store 2 4
  , Custom $ CallSym "#eval"
  , End
  ]
allocAsm :: [QuasiWasm]
allocAsm =
  [ Loop Nada
    [ Get_local 0  -- Break when local0 == 0
    , I32_eqz
    , Br_if 1
    , Get_local 0  -- local0 = local0 - 1
    , I32_const 1
    , I32_sub
    , Set_local 0
    , Get_global hp  -- #push32 hp
    , Custom $ CallSym "#push32"
    , Get_global hp  -- [hp] = TagInd
    , tag_const TagInd
    , I32_store 2 0
    , Get_global hp  -- hp = hp + 8
    , I32_const 8
    , I32_add
    , Set_global hp
    , Br 0
    ]
  , End
  ]
updateIndAsm :: [WasmOp]
updateIndAsm =
  [ Get_global sp  -- sp = sp + 4
  , I32_const 4
  , I32_add
  , Set_global sp
  -- local0 should be 4*(n + 1)
  , Get_global sp  -- [[sp + local0] + 4] = [sp]
  , Get_local 0
  , I32_add
  , I32_load 2 0
  , Get_global sp
  , I32_load 2 0
  , I32_store 2 4
  , End
  ]

pairWith42Asm :: [WasmOp]
pairWith42Asm =  -- [sp + 4] = (local0, #RealWorld)
  [ Get_global hp  -- [hp] = (TagSum | (2 << 8)).64
  , I64_const $ fromIntegral $ fromEnum TagSum + 256 * 2
  , I64_store 3 0
  , Get_global hp  -- [hp + 8] = local0
  , Get_local 0
  , I32_store 2 8
  , Get_global hp  -- [hp + 12] = 42
  , I32_const 42
  , I32_store 2 12
  , Get_global sp  -- [sp + 4] = hp
  , Get_global hp
  , I32_store 2 4
  , Get_global hp  -- hp = hp + 16
  , I32_const 16
  , I32_add
  , Set_global hp
  , End
  ]
-- | [sp + 4] = ((), #RealWorld)
-- TODO: Optimize by placing this special value at a known location in memory.
nil42Asm :: [QuasiWasm]
nil42Asm =
  [ Get_global hp  -- [hp].64 = TagSum
  , I64_const $ fromIntegral $ fromEnum TagSum
  , I64_store 3 0
  , Get_global hp  -- PUSH hp
  , Get_global hp  -- hp = hp + 8
  , I32_const 8
  , I32_add
  , Set_global hp
  , Custom $ CallSym "#pairwith42"
  , End
  ]

toWasmType :: Type -> WasmType
toWasmType (TC "Int") = I64
toWasmType _ = I32

addHelper :: [Type] -> [[Ins]] -> State CompilerState ()
addHelper ty ms = do
  st <- get
  put st { helpers = (show ty, f):helpers st }
  where
  f = case (ty, ms) of
    ([t], [encoder]) ->
      -- When sending a message with only one item, we have a bare argument
      -- instead of an argument tuple
      -- Evaluate single argument.
      [ Push 1
      , WasmPush encoder t
      , Push 0  -- Slot.
      , Eval
      , WasmCallIndirect ty
      ]
    _ ->
      -- Evaluate argument tuple.
      [ Push 1
      , Eval
      , Split $ length ms
      ] ++ zipWith WasmPush ms ty ++
      [ Push 0  -- Slot.
      , Eval
      , WasmCallIndirect ty
      ]


================================================
FILE: src/Ast.hs
================================================
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DeriveGeneric #-}
module Ast
  ( Ast(..)
  , AAst(..)
  , AstF(..)
  , deAnn
  , bifix
  , ffix
  , Type(..)
  ) where

import Data.Binary (Binary)
#ifndef __HASTE__
import Data.ByteString.Short (ShortByteString)
#endif
import Data.Int
import GHC.Generics (Generic)

#ifdef __HASTE__
type ShortByteString = String
#endif

instance Binary Type

infixl 5 :@
data AstF a = Qual String String
  | CallSlot [Type] [a]
  | Pack Int Int | I Int64 | S ShortByteString | Var String
  | a :@ a | Cas a [(a, a)]
  | Lam [String] a | Let [(String, a)] a
  | DictIndex Int | Placeholder String Type
  deriving (Read, Show, Functor, Foldable, Traversable, Generic)

newtype Ast = Ast (AstF Ast) deriving (Show, Generic)

-- Annotated AST.
data AAst a = AAst a (AstF (AAst a)) deriving (Show, Functor)

deAnn :: AAst a -> Ast
deAnn = ffix $ \h (AAst _ ast) -> Ast $ h ast

bifix :: (a -> b) -> (b -> a) -> a
bifix g f = f $ g $ bifix g f

ffix :: Functor f => ((f a -> f b) -> a -> b) -> a -> b
ffix = bifix fmap

infixr 5 :->
data Type = TC String | TApp Type Type | Type :-> Type
  | TV String | GV String deriving (Read, Show, Eq, Generic)


================================================
FILE: src/Boost.hs
================================================
{-# LANGUAGE CPP #-}
module Boost
  ( QuasiWasm
  , QuasiWasmHelper(..)
  , tag_const, Tag(..)
  , Boost(..)
#ifdef __HASTE__
  , (<>)
#endif
  ) where

#ifndef __HASTE__
import Data.Semigroup ()
#endif

import Ast
import WasmOp

-- | Data on the heap is 64-bit aligned. The first 8 bits hold a tag.
--
-- The following tables describe the field at a given offset of an object
-- on the heap. All fields are 32 bits wide except the value field of a 64-bit
-- integer type.
--
-- Int64s:
--    0 TagInt
--    8 64-bit value
--
-- Ports:
--    0 TagRef
--    4 32-bit value
--
-- Coproduct (sum) types:
--    0 TagSum | (arity << 8)
--    4 Enum
--    8, 12.. Heap addresses of components.
--
-- Application `f x`:
--    0 TagAp
--    4 Unused
--    8 f
--   12 x
--
-- Global function:
--    0 TagGlobal | (arity << 8)
--    4 Function index
--
-- Indirection:
--    0 TagInd
--    4 Heap address of target
--
-- String:
--    0 TagString
--    4 address
--    8 offset
--    12 length
--
-- For example, `Just 42` is represented by:
--
--   [TagSum, 1, p], where p points to [TagInt, 0, 42]
--
-- where each list item is a 32-bit integer.

data Tag = TagAp | TagInd | TagGlobal | TagInt | TagRef | TagSum | TagString deriving Enum

tag_const :: Tag -> CustomWasmOp a
tag_const = I32_const . fromIntegral . fromEnum

-- | A few helpers for inline assembly.
type QuasiWasm = CustomWasmOp QuasiWasmHelper
data QuasiWasmHelper =
    CallSym String  -- Find function index and call it.
  | ReduceArgs Int  -- Copy arguments from heap and reduce them to WHNF.
  deriving Show

type WasmImport = ((String, String), ([WasmType], [WasmType]))

-- | A Boost is a custom collection of extra declarations and functions that
-- are added to a binary.
data Boost = Boost
  -- Wasm import declarations.
  { boostImports :: [WasmImport]
  -- Haskell definitions.
  , boostPrelude :: String
  -- Primitive Haskell functions.
  , boostPrims :: [(String, (Type, [QuasiWasm]))]
  -- Internal wasm functions, indexed by strings for CallSym.
  , boostWasm :: [(String, (([WasmType], [WasmType]), [QuasiWasm]))]
  }

#ifdef __HASTE__
(<>) :: Boost -> Boost -> Boost
Boost a b c d <> Boost x y z w = Boost (a ++ x) (b ++ y) (c ++ z) (d ++ w)
#else
instance Semigroup Boost where
  Boost a b c d <> Boost x y z w = Boost (a <> x) (b <> y) (c <> z) (d <> w)

instance Monoid Boost where
  mempty = Boost [] [] [] []
  mappend = (<>)
#endif


================================================
FILE: src/DHC.hs
================================================
{-# LANGUAGE CPP #-}
#ifdef __HASTE__
{-# LANGUAGE PackageImports #-}
#endif
module DHC
  ( AstF(..), Ast(..), Clay(..), Type(..)
  , parseDefs
  , arityFromType, hsToAst, liftLambdas
  ) where
import Control.Arrow
import Control.Monad
#ifdef __HASTE__
import "mtl" Control.Monad.State
#else
import Control.Monad.Reader
import Control.Monad.State
#endif
import Data.Char
import Data.List
import qualified Data.Map.Strict as M
import Data.Map.Strict (Map)
import Data.Maybe
import Data.Traversable

import Ast
import Boost
import Parse

type QualType = (Type, [(String, String)])
data Clay = Clay
  -- Public and secret functions are accompanied by a list of their
  -- arguments types and a program for decoding them from the heap.
  { publics :: [(String, [(Type, Ast)])]
  , secrets :: [(String, [(Type, Ast)])]
  , stores :: [(String, Type)]
  , funTypes :: Map String QualType
  , supers :: Map String Ast
  , genDecls :: [(String, Type)]
  , datas :: Map String (Maybe (Int, Int), Type)
  -- | e.g. "==" -> (type "a -> a -> Bool", 0, ("Eq", "a"))
  -- The number is the method's index in the sorted list of methods.
  , methods :: Map String (Type, Int, (String, String))
  -- | e.g. "Monad" -> [">>=", "pure"]. List is sorted.
  , classes :: Map String [String]
  -- We delay processing instance declarations until after all class
  -- definitions have been handled, including those from the prelude.
  , preInstances :: [([(String, String)], String, Type, [(String, Ast)])]
  -- | e.g. "Monad" ->
  --   [ (TC "Maybe", Ast of tuple (maybe->>=, maybe-pure))
  --   , (TC "IO", Ast of tuple (io->>=, io-pure))
  --   ]
  , instances :: Map String [(QualType, Ast)]
  , recursiveCompile :: String -> String
  }

newClay :: (String -> String) -> [TopLevel] -> Either String Clay
newClay rCompile ts = do
  p0 <- foldM f emptyClay ts
  let missing = (fst <$> publics p0) \\ M.keys (supers p0)
  unless (null missing) $ Left $ "missing public functions: " ++ show missing
  let
    storeCons s
      | Just ty <- lookup s $ genDecls p0 = (s, ty)
      | otherwise = (s, TC "Store" `TApp` TV ('@':s))
  pure $ p0 { stores = storeCons . fst <$> stores p0 }
  where
  emptyClay = Clay [] [] [] M.empty M.empty [] M.empty M.empty M.empty [] M.empty rCompile
  f p t = case t of
    Super (name, ast) -> Right p { supers = M.insert name ast $ supers p }
    ClassDecl s ty unsorted -> Right p
      { methods = m1
      , classes = M.insert s (fst <$> xs) $ classes p
      }
      where
      xs = sortOn fst unsorted
      m1 = foldl' addMethod (methods p) $ zip [0..] xs
      addMethod m (idx, (mName, mType)) = M.insert mName (mType, idx, (s, ty)) m
    InstanceDecl ctx cl ty is -> Right p
      { preInstances = (ctx, cl, ty, sortOn fst is):preInstances p }
    GenDecl x -> Right p { genDecls = x:genDecls p }
    DataDecl xs -> Right p { datas = foldl' (\m (k, v) -> M.insert k v m) (datas p) xs }
    PublicDecl xs -> Right p { publics = zip xs $ repeat [] }
    StoreDecl xs -> Right p { stores = zip xs $ repeat undefined }

-- | Adds a dictionary object for a given instance, along with supercombinators
-- for each of the method implementations.
--
-- A dictionary is a tuple of `Var` nodes that refer to this instance's
-- implementation of the methods, ordered lexicographically.
-- Must be run after processing class declarations.
--
-- If there is only one method in the typeclass, then instead of a tuple of
-- size 1, we generate a single Var node.
--
-- For example, the Maybe Monad instance results in the tuple:
--
--   (Var "Maybe->>=", Var "Maybe-pure")
--
-- along with the supercombinators:
--
--   (Maybe->>=) x f = case x of { Nothing -> Nothing; Just a -> f a }
--   (Maybe-pure) x = Just x"
--
-- Actually, the generated prefixes are uglier because we just use `show`,
-- which produces "TC \"Maybe\"" instead of "Maybe".
mkDict :: Clay -> ([(String, String)], String, Type, [(String, Ast)]) -> Either String Clay
mkDict p (ctx, cls, ty, is) = case M.lookup cls $ classes p of
  Nothing -> Left $ "unknown typeclass: " ++ cls
  Just ms -> do
    when (sorted /= ms) $ Left $ "instance methods disagree with class: " ++ cls ++ " " ++ show ty
    Right p
      { instances = M.insertWith (++) cls [((ty, ctx), dict)] $ instances p
      , supers = supers p `M.union` M.fromList (first (methodPrefix ty) <$> is)
      }
    where
    dict | [one] <- sorted = Ast $ Var $ methodPrefix ty one
         | otherwise = foldl' ((Ast .) . (:@)) (Ast $ Pack 0 $ length is) $ Ast . Var . methodPrefix ty <$> sorted
    sorted = sort $ fst <$> is

methodPrefix :: Type -> String -> String
methodPrefix ty method = concat [show ty, "-", method]

hsToAst :: Boost -> QQuoter -> String -> Either String Clay
hsToAst boost qq prog = do
  cl0 <- showErr $ newClay (either error id . qq "wasm") =<< either (Left . show) Right (parseDfnHs qq prog)
  preludeDefs <- parseDefs $ boostPrelude boost
  let
    cl1 = extractSecrets cl0
      { supers = supers preludeDefs `M.union` supers cl0
      , datas = datas preludeDefs `M.union` datas cl0
      , methods = methods preludeDefs `M.union` methods cl0
      , classes = classes preludeDefs `M.union` classes cl0
      , preInstances = preInstances preludeDefs ++ preInstances cl0
      }
  cl <- foldM mkDict cl1 $ preInstances cl1
  (inferred, storageCons) <- inferType boost cl
  let
    -- TODO: Handle non-strict case expressions.
    subbedDefs =
        (second expandCase <$>)
      . liftLambdas
      -- Saturating constructors may create lambdas, so must occur before
      -- we lift lambdas.
      . (second saturateCons <$>)
      . (second snd <$>) $ inferred
    types = M.fromList $ second fst <$> inferred
    stripStore (TApp (TC "Store") t) = t
    stripStore _ = error "expect Store"
    addDecoders :: String -> (String, [(Type, Ast)])
    addDecoders s = (s, addDec [] ty)
      where
      Just (ty, _) = M.lookup s types
      addDec acc t = case t of
        a :-> b -> addDec ((a, dictSolve inferred cl [] M.empty $ Ast (Placeholder "dfromUnboxed" a)) : acc) b
        TApp (TC "IO") (TC "()") -> reverse acc
        _ -> error "exported functions must return IO ()"
  pure cl
    { publics = addDecoders . fst <$> publics cl
    , secrets = addDecoders . fst <$> secrets cl
    , supers = M.fromList subbedDefs
    , funTypes = types
    , stores = second (stripStore . typeSolve storageCons) <$> stores cl }
  where
  showErr = either (Left . show) Right

justHere :: QQuoter
justHere "here" s = Right s
justHere _ _ = Left "bad scheme"

parseDefs :: String -> Either String Clay
parseDefs s = newClay undefined =<< either (Left . show) Right (parseDfnHs justHere s)

-- The Constraints monad combines a State monad and an Either monad.
-- The state consists of the set of constraints and next integer available
-- for naming a free variable, and the contexts of each variable.
data ConState = ConState
  String -- Prefix for generated free variables.
  Int  -- Integer for next free variable name.
  [(Type, Type)]  -- Constraints added so far.
  (Map String [String])  -- Contexts of each variable.
newtype Constraints a = Constraints (ConState -> Either String (a, ConState))

buildConstraints :: String -> Constraints a -> Either String (a, ConState)
buildConstraints pre (Constraints f) = f $ ConState pre 0 [] M.empty

instance Functor Constraints where fmap = liftM
instance Applicative Constraints where { (<*>) = ap ; pure = return }
instance Monad Constraints where
  Constraints c1 >>= fc2 = Constraints $ \cs -> case c1 cs of
    Left err -> Left err
    Right (r, cs2) -> let Constraints c2 = fc2 r in c2 cs2
  return a = Constraints $ \p -> Right (a, p)

newTV :: Constraints Type
newTV = Constraints $ \(ConState pre i cs m) -> Right (TV $ pre ++ show i, ConState pre (i + 1) cs m)

addConstraint :: (Type, Type) -> Constraints ()
addConstraint c = Constraints $ \(ConState pre i cs m) -> Right ((), ConState pre i (c:cs) m)

addContext :: String -> String -> Constraints ()
addContext s x = Constraints $ \(ConState pre i cs m) -> Right ((), ConState pre i cs $ M.insertWith union x [s] m)

type Globals = Map String (Maybe (Int, Int), Type)

-- | Gathers constraints.
-- Replaces overloaded methods with Placeholder.
-- Replaces data constructors with Pack.
-- For DFINITY, replaces `my.f` with `#preslot n` where n is the slot number
-- preloaded with the secret or public function `f`.
gather
  :: Clay
  -> Globals
  -> [(String, QualType)]
  -> Ast
  -> Constraints (AAst Type)
gather cl globs env (Ast ast) = case ast of
  I i -> pure $ AAst (TC "Int") $ I i
  S s -> pure $ AAst (TC "String") $ S s
  Pack m n -> do  -- Only tuples are pre`Pack`ed.
    xs <- replicateM n newTV
    let r = foldr1 TApp $ TC "()":xs
    pure $ AAst (foldr (:->) r xs) $ Pack m n
  Qual "my" f
    | Just n <- elemIndex f (fst <$> publics cl ++ secrets cl) -> rec env $ Ast (Ast (Var "#preslot") :@ Ast (I $ fromIntegral n))
    | otherwise -> bad $ "must be secret or public: " ++ f
  Var "_" -> do
    x <- newTV
    pure $ AAst x $ Var "_"
  Var v
    | Just qt <- lookup v env -> do
      (t1, qs1) <- instantiate qt
      pure $ foldl' ((AAst t1 .) . (:@)) (AAst t1 $ Var v) $ (\(a, b) -> AAst (TC $ "Dict-" ++ a) $ Placeholder a (TV b)) <$> qs1
    | Just (ty, _, typeClass) <- M.lookup v $ methods cl -> do
      ~(t1, [(_, x)]) <- instantiate (ty, [typeClass])
      pure $ AAst t1 $ Placeholder v $ TV x
    | Just (ma, gt) <- M.lookup v globs ->
      flip AAst (maybe (Var v) (uncurry Pack) ma) . fst <$> instantiate (gt, [])
    | otherwise -> bad $ "undefined: " ++ v
  t :@ u -> do
    a@(AAst tt _) <- rec env t
    b@(AAst uu _) <- rec env u
    x <- newTV
    addConstraint (tt, uu :-> x)
    pure $ AAst x $ a :@ b
  Lam args u -> do
    ts <- mapM (const newTV) args
    a@(AAst tu _) <- rec (zip (filter (/= "_") args) (zip ts $ repeat []) ++ env) u
    pure $ AAst (foldr (:->) tu ts) $ Lam args a
  Cas e as -> do
    aste@(AAst te _) <- rec env e
    x <- newTV
    astas <- forM as $ \(p, a) -> do
      let
        varsOf (Ast (t :@ u)) = varsOf t ++ varsOf u
        varsOf (Ast (Var v)) | isLower (head v) = [v]
        varsOf _ = []
      when (varsOf p /= nub (varsOf p)) $ bad "multiple binding in pattern"
      envp <- forM (varsOf p) $ \s -> (,) s . flip (,) [] <$> newTV
      -- TODO: Check p is a pattern.
      astp@(AAst tp _) <- rec (envp ++ env) p
      addConstraint (te, tp)
      asta@(AAst ta _) <- rec (envp ++ env) a
      addConstraint (x, ta)
      pure (astp, asta)
    pure $ AAst x $ Cas aste astas
  Let ds body -> do
    es <- forM (fst <$> ds) $ \s -> (,) s <$> newTV
    let envLet = (second (flip (,) []) <$> es) ++ env
    ts <- forM (snd <$> ds) $ rec envLet
    mapM_ addConstraint $ zip (snd <$> es) (afst <$> ts)
    body1@(AAst t _) <- rec envLet body
    pure $ AAst t $ Let (zip (fst <$> ds) ts) body1
  _ -> fail $ "BUG! unhandled: " ++ show ast
  where
    rec = gather cl globs
    bad = Constraints . const . Left
    afst (AAst t _) = t

-- | Instantiate generalized variables.
-- Returns type where all generalized variables have been instantiated along
-- with the list of type constraints where each generalized variable has
-- been instantiated with the same generated names.
instantiate :: QualType -> Constraints (Type, [(String, String)])
instantiate (ty, qs) = do
  (gvmap, result) <- f [] $ subStore ty
  let qInstances = second (getVar gvmap) <$> qs
  forM_ qInstances $ uncurry addContext
  pure (result, qInstances)
  where
  getVar m v = x where Just (TV x) = lookup v m
  f m (GV s) | Just t <- lookup s m = pure (m, t)
             | otherwise = do
               x <- newTV
               pure ((s, x):m, x)
  f m (t :-> u) = do
    (m1, t') <- f m t
    (m2, u') <- f m1 u
    pure (m2, t' :-> u')
  f m (t `TApp` u) = do
    (m1, t') <- f m t
    (m2, u') <- f m1 u
    pure (m2, t' `TApp` u')
  f m t = pure (m, t)

-- Change "Store a" -> "(AnyDfn -> IO (), IO AnyDfn)".
subStore :: Type -> Type
subStore ty = case ty of
  t :-> u -> subStore t :-> subStore u
  TC "Store" `TApp` u -> TApp (TC "()") $
    (unboxed (subStore u) :-> io (TC "()")) `TApp` io (unboxed $ subStore u)
  t `TApp` u -> subStore t `TApp` subStore u
  _ -> ty
  where
  io = TApp $ TC "IO"
  unboxed = TApp $ TC "Unboxed"

generalize
  :: [(String, (QualType, Ast))]
  -> Clay
  -> Solution
  -> (String, AAst Type)
  -> (String, (QualType, Ast))
generalize scs cl (soln, ctx) (fun, a0@(AAst t0 _)) = (fun, (qt, a1)) where
  qt@(_, qs) = runState (generalize' ctx $ typeSolve soln t0) []
  -- TODO: Compute nub of qs?
  dsoln = zip qs $ ("#d" ++) . show <$> [(0::Int)..]
  -- TODO: May be useful to preserve type annotations?
  a1 = dictSolve scs cl dsoln soln ast
  dvars = snd <$> dsoln
  ast = case deAnn a0 of
    Ast (Lam ss body) -> Ast $ Lam (dvars ++ ss) $ expandFun body
    body -> Ast $ Lam dvars $ expandFun body
  -- TODO: Take shadowing into account.
  expandFun
    | null dvars = id
    | otherwise  = ffix $ \h (Ast a) -> Ast $ case a of
      Var v | v == fun -> foldl' (\x d -> (Ast x :@ Ast (Var d))) a dvars
      _ -> h a

-- Replaces e.g. `TV x` with `GV x` and adds its constraints
-- (e.g. Eq x, Monad x) to the common pool.
generalize' :: Map String [String] -> Type -> State [(String, String)] Type
generalize' ctx ty = case ty of
  TV s -> do
    case M.lookup s ctx of
      Just cs -> modify' $ union $ flip (,) s <$> cs
      Nothing -> pure ()
    pure $ GV s
  u :-> v  -> (:->) <$> generalize' ctx u <*> generalize' ctx v
  TApp u v -> TApp  <$> generalize' ctx u <*> generalize' ctx v
  _        -> pure ty

dictSolve
  :: [(String, (QualType, Ast))]
  -> Clay
  -> [((String, String), String)]
  -> Map String Type
  -> Ast
  -> Ast
dictSolve scs cl dsoln soln = ffix $ \h (Ast ast) -> case ast of
  -- Replace method Placeholders with selector and dictionary Placeholder.
  Placeholder s t | Just (_, idx, (typeClass, _)) <- M.lookup s $ methods cl ->
    case length $ classes cl M.! typeClass of
      1 -> rec (Ast $ Placeholder typeClass $ typeSolve soln t)
      _ -> Ast (DictIndex idx) @@ rec (Ast $ Placeholder typeClass $ typeSolve soln t)
  -- Replace dictionary Placeholders.
  Placeholder d t -> case typeSolve soln t of
    TV v -> Ast $ Var $ fromMaybe (error $ "unsolvable: " ++ show (d, v)) $ lookup (d, v) dsoln
    u -> findInstance d u
  _       -> Ast $ h ast
  where
  aVar = Ast . Var
  infixl 5 @@
  x @@ y = Ast $ x :@ y
  rec = dictSolve scs cl dsoln soln
  findInstance typeClass t | Just insts <- M.lookup typeClass $ instances cl
    = case matchInstance typeClass t insts of
      Nothing -> error "BUG! missing instance"
      Just ast -> rec ast
  findInstance "Message" t = Ast . CallSlot tu $ rec . Ast . Placeholder "ctoUnboxed" <$> tu
    where tu = either (error . show) id $ listFromTupleType t
  -- The "Storage" typeclass has four methods:
  --  1. toAnyRef
  --  2. fromAnyRef
  --  3. toUnboxed
  --  4. fromUnboxed
  -- For boxed types such as databufs, 1 and 2 are the same as 3 and 4.
  -- For unboxed types, such as integers, 1 encodes to a databuf, 2 decodes
  -- from a databuf, and 3 and 4 leave the input unchanged.
  findInstance "Storage" t = case t of
    TC "Databuf" -> boxy (aVar "#reduce") (aVar "#reduce")
    TC "String" -> boxy (aVar "." @@ aVar "#reduce" @@ aVar "toD") (aVar "." @@ aVar "#reduce" @@ aVar "fromD")
    TC "Port" -> boxy (aVar "#reduce") (aVar "#reduce")
    TC "Actor" -> boxy (aVar "#reduce") (aVar "#reduce")
    TC "Module" -> boxy (aVar "#reduce") (aVar "#reduce")
    TC "Int" -> Ast (Pack 0 4) @@ aVar "Int-toAny" @@ aVar "Int-fromAny" @@ aVar "#reduce" @@ aVar "#reduce"
    TC "I32" -> Ast (Pack 0 4) @@ aVar "#reduce" @@ aVar "#reduce" @@ aVar "#reduce" @@ aVar "#reduce"
    TC "Bool" -> Ast (Pack 0 4) @@ aVar "Bool-toAny" @@ aVar "Bool-fromAny" @@ aVar "Bool-toUnboxed" @@ aVar "Bool-fromUnboxed"
    TApp (TC "[]") a -> let
      ltai = aVar "list_to_any_instance" @@ rec (Ast $ Placeholder "Storage" a)
      lfai = aVar "list_from_any_instance" @@ rec (Ast $ Placeholder "Storage" a)
      in boxy ltai lfai
    TC "()" -> boxy (aVar "unit_to_any_instance") (aVar "unit_from_any_instance")
    TApp (TC "()") (TApp a b) -> let
      -- TODO: Brittle. Relies on order constraints are found.
      -- Implement contexts for instance declarations.
      ptai = aVar "pair_to_any_instance" @@ rec (Ast $ Placeholder "Storage" b) @@ rec (Ast $ Placeholder "Storage" a)
      pfai = aVar "pair_from_any_instance" @@ rec (Ast $ Placeholder "Storage" b) @@ rec (Ast $ Placeholder "Storage" a)
      in boxy ptai pfai
    e -> error $ "BUG! no Storage for " ++ show e
    where boxy to from = Ast (Pack 0 4) @@ to @@ from @@ to @@ from
  findInstance d t = error $ "BUG! bad class: " ++ show (d, t)

  matchInstance typeClass t candidates = do
    ((sol, ctx), (qt, ast)) <- lookupType cl t candidates
    let
      Just classMethods = M.lookup typeClass $ classes cl
      mAsts = mkDictEntry <$> classMethods
      -- TODO: Respect the order of the clauses in the context of `qt`.
      mkDictEntry moo = foldl' addDict (Ast $ Var $ methodPrefix (fst qt) moo) $ M.assocs ctx
      addDict a (zzz, [xxx]) = case typeSolve sol (TV zzz) of
        TV v -> let Just dv = lookup (xxx, v) dsoln
          in Ast $ a :@ Ast (Var dv)
        tt -> Ast $ a :@ Ast (Placeholder xxx tt)
      addDict _ _ = error "TODO: more than one constraint per type variable"
    case () of
      () | M.null sol -> Just ast
         | [mAst] <- mAsts -> Just mAst
         | otherwise -> Just $ foldl' ((Ast .) . (:@)) (Ast $ Pack 0 $ length classMethods) mAsts

typeSolve :: Map String Type -> Type -> Type
typeSolve soln t = case t of
  TApp a b      -> rec a `TApp` rec b
  a :-> b       -> rec a :-> rec b
  TV x          -> fromMaybe t $ M.lookup x soln
  _             -> t
  where rec = typeSolve soln

lookupType :: Clay -> Type -> [(QualType, Ast)] -> Maybe (Solution, (QualType, Ast))
lookupType _ _ [] = Nothing
lookupType cl t ((qt, ast):rest) = case unify cl cs m of
  Left _ -> lookupType cl t rest
  Right zzz -> Just (zzz, (qt, ast))
  where
  Right (_, ConState _ _ cs m) = buildConstraints "#" $ do
    (ty, _) <- instantiate qt
    addConstraint (ty, t)
    pure ()

-- | The `propagateClasses` and `propagateClassTyCon` functions of
-- "Implementing type classes".
propagate :: Clay -> [String] -> Type -> Either String [(String, [String])]
propagate _ [] _ = Right []
propagate _ cs (TV y) = Right [(y, cs)]
propagate cl cs t = concat <$> mapM propagateTyCon cs where
  propagateTyCon s | Just insts <- M.lookup s $ instances cl = case lookupType cl t insts of
    Nothing -> Left $ unwords ["no", s, "instance:", show t]
    -- For example, given `Eq [a]`, returns `Eq a`.
    Just ((_, ctx), _) -> Right $ M.assocs ctx
  propagateTyCon "Storage" = case t of
    TApp (TC "()") (TApp a b) -> (++) <$> rec ["Storage"] a <*> rec ["Storage"] b
    TApp (TC "[]") a -> rec ["Storage"] a
    TC s | elem s messageTypes -> Right []
    _ -> Left $ "no Storage instance: " ++ show t
  propagateTyCon "Message" =
    concat <$> (mapM (rec ["Storage"]) =<< listFromTupleType t)
  propagateTyCon c = error $ "TODO: " ++ c
  rec = propagate cl

-- | Returns list of types from a tuple.
-- e.g. (String, Int) becomes [String, Int]
-- This should be trivial, but we represent tuples in a weird way!
listFromTupleType :: Type -> Either String [Type]
listFromTupleType ty = case ty of
  TC "()" -> Right []
  TApp (TC "()") rest -> weirdList rest
  _ -> Right [ty]
  where
  -- Tuples are represented oddly in our Type data structure.
  weirdList tup = case tup of
    TC _ -> Right [tup]
    TV _ -> Right [tup]
    TApp h@(TC _) rest -> (h:) <$> weirdList rest
    TApp h@(TV _) rest -> (h:) <$> weirdList rest
    _ -> Left $ "want tuple: " ++ show tup

-- e.g. [TV 'a' -> TC "Int", ...], [TV 'b', ["Eq", "Ord"], ...]
type Solution = (Map String Type, Map String [String])

unify :: Clay -> [(Type, Type)] -> Map String [String] -> Either String Solution
unify cl constraints ctx = execStateT (uni cl constraints) (M.empty, ctx)

refine :: Clay -> [(Type, Type)] -> Solution -> Either String Solution
refine cl constraints = execStateT (uni cl constraints)

uni :: Clay -> [(Type, Type)] -> StateT (Map String Type, Map String [String]) (Either String) ()
uni _ [] = do
  (tm, qm) <- get
  as <- forM (M.keys tm) $ follow . TV
  put (M.fromList $ zip (M.keys tm) as, qm)
uni _ ((GV _, _):_) = lift $ Left "BUG! generalized variable in constraint"
uni _ ((_, GV _):_) = lift $ Left "BUG! generalized variable in constraint"
uni cl ((lhs, rhs):cs) = do
  z <- (,) <$> follow lhs <*> follow rhs
  case z of
    (s, t) | s == t -> rec cs
    (TV x, TV y) -> do
      when (x /= y) $ do
        (tm, qm) <- get
        -- (Ideally should union by rank.)
        put (M.insert x (TV y) tm, case M.lookup x qm of
          Just q -> M.insert y q $ M.delete x qm
          _ -> qm)
      rec cs
    (TV x, t) -> if x `elem` freeTV t
      -- TODO: Test infinite type detection.
      then lift . Left $ "infinite: " ++ x ++ " = " ++ show t
      else do
        -- The `instantiateTyvar` function of "Implementing type classes".
        (_, qm) <- get
        -- For example, Eq [a] propagates to Eq a, which we record.
        either (lift . Left) addQuals $ propagate cl (fromMaybe [] $ M.lookup x qm) t
        modify' $ first $ M.insert x t
        rec cs
    (s, t@(TV _)) -> rec $ (t, s):cs
    (TApp s1 s2, TApp t1 t2) -> rec $ (s1, t1):(s2, t2):cs
    (s1 :-> s2, t1 :-> t2) -> rec ((s1, t1):(s2, t2):cs)
    (s, t) -> lift . Left $ "mismatch: " ++ show s ++ " /= " ++ show t
  where
  addQuals = modify' . second . M.unionWith union . M.fromList
  rec = uni cl

-- Galler-Fischer-esque Data.Map (path compression).
follow :: Type -> StateT (Map String Type, a) (Either String) Type
follow t = case t of
  TApp a b -> TApp <$> follow a <*> follow b
  a :-> b  -> (:->) <$> follow a <*> follow b
  TV x     -> do
    (tm, qm) <- get
    case M.lookup x tm of
      Just u -> do
        z <- follow u
        put (M.insert x z tm, qm)
        pure z
      Nothing -> pure $ TV x
  _        -> pure t
freeTV :: Type -> [String]
freeTV t = case t of
  TApp a b -> freeTV a ++ freeTV b
  a :-> b  -> freeTV a ++ freeTV b
  TV tv    -> [tv]
  _        -> []

arityFromType :: Type -> Int
arityFromType = f 0 where
  f acc (_ :-> r) = f (acc + 1) r
  f acc _ = acc

boostTypes :: Boost -> Map String (Maybe (Int, Int), Type)
boostTypes b = M.fromList $ second ((,) Nothing . fst) <$> boostPrims b

-- | Find functions used as funrefs but not declared public.
extractSecrets :: Clay -> Clay
extractSecrets cl = cl { secrets = zip (concatMap filterSecrets $ M.elems $ supers cl) $ repeat [] }
  where
  filterSecrets = bifix foldMapDefault $ \h (Ast ast) -> case ast of
    Qual "my" f -> if elem f $ fst <$> publics cl then [] else [f]
    _ -> h ast

inferType
  :: Boost
  -> Clay
  -- Returns types of definitions and stores.
  -> Either String ([(String, (QualType, Ast))], Map String Type)
inferType boost cl = foldM inferMutual ([], M.empty) $ map (map (\k -> (k, ds M.! k))) sortedDefs where
  ds = supers cl
  -- Groups of definitions, sorted in the order we should infer their types.
  sortedDefs = reverse $ scc (callees cl ds) $ M.keys ds
  -- List notation is a special case in Haskell.
  -- This is "data [a] = [] | a : [a]" in spirit.
  listPresets = M.fromList
    [ ("[]", (Just (0, 0), TApp (TC "[]") a))
    , (":",  (Just (1, 2), a :-> TApp (TC "[]") a :-> TApp (TC "[]") a))
    ] where a = GV "a"
  globs = listPresets
    `M.union` datas cl
    `M.union` boostTypes boost
    `M.union` M.fromList (second ((,) Nothing) <$> stores cl)
  inferMutual :: ([(String, (QualType, Ast))], Map String Type) -> [(String, Ast)] -> Either String ([(String, (QualType, Ast))], Map String Type)
  inferMutual (acc, accStorage) grp = do
    (typedAsts, ConState _ _ cs m) <- buildConstraints "_" $ forM grp $ \(s, d) -> do
      t <- gather cl globs env d
      addConstraint (TV $ '*':s, annOf t)
      when (s == "main") $ addConstraint (TV $ '*':s, TApp (TC "IO") $ TC "()")
      case s `lookup` genDecls cl of
        Nothing -> pure ()
        Just gt -> do
          (ty, _) <- instantiate (gt, [])
          addConstraint (TV $ '*':s, ty)
      pure (s, t)
    initSol <- unify cl cs m
    sol@(solt, _) <- foldM (checkPubSecs cl) initSol (fst <$> grp)
    let storageCons = M.filterWithKey (\k _ -> head k == '@') solt
    -- TODO: Look for conflicting storage constraints.
    pure ((++ acc) $ generalize acc cl sol <$> typedAsts, accStorage `M.union` storageCons)
    where
    annOf (AAst a _) = a
    tvs = TV . ('*':) . fst <$> grp
    env = zip (fst <$> grp) (zip tvs $ repeat []) ++ map (second fst) acc

checkPubSecs :: Clay -> Solution -> String -> Either String Solution
checkPubSecs cl (soln, ctx) s
  | s /= "main" &&  -- Already handled.
      (s `elem` (fst <$> publics cl ++ secrets cl)) =
    -- Require `public` and `secret` functions to return IO ().
    refine cl [(retType t, TApp (TC "IO") (TC "()"))] (soln, ctx)
    -- TODO: Check no free variables are left, and
    -- propagate ["Storage"] succeeds (returns []) for each argument type.
  | otherwise = Right (soln, ctx)
  where
  Just t = M.lookup ('*':s) soln
  retType (_ :-> a) = retType a
  retType r = r

-- TODO: For finding strongly-connected components, there's no need to find
-- all dependencies. If a node has already been processed, we should avoid
-- finding all its dependencies again. We can do this by passing in a list of
-- nodes that have already been explored.
callees :: Clay -> Map String Ast -> String -> [String]
callees cl ds s = snd $ execState (go s) ([], []) where
  go :: String -> State ([String], [String]) ()
  go f = do
    (env, acc) <- get
    unless (elem f (env ++ acc) || M.member f (methods cl)) $ case M.lookup f ds of
      -- TODO: If we knew the primitives (functions implemented in wasm, such
      -- as `*`), then we could detect out-of-scope identifiers here.
      Nothing -> pure ()  -- error $ "not in scope: " ++ f
      Just d -> do
        put (env, f:acc)
        ast d
  ast (Ast d) = case d of
    x :@ y -> ast x >> ast y
    Lam ss t -> do
      env <- gets fst
      modify $ first (ss ++)
      ast t
      modify $ first (const env)
    Var v -> go v
    Cas x as -> do
      ast x
      forM_ as $ \(Ast p, e) -> do
        env <- gets fst
        modify $ first (caseVars p ++)
        ast e
        modify $ first (const env)
    Let as x -> do
      env <- gets fst
      modify $ first ((fst <$> as) ++)
      mapM_ ast $ snd <$> as
      ast x
      modify $ first (const env)
    _ -> pure ()

-- | Returns strongly connected components in topological order.
scc :: Eq a => (a -> [a]) -> [a] -> [[a]]
scc suc vs = foldl' (\cs v -> assign cs [] v : cs) [] $ reverse $ topo suc vs where
  assign cs c v | any (elem v) $ c:cs = c
                | otherwise           = foldl' (assign cs) (v:c) (suc v)

topo :: Eq a => (a -> [a]) -> [a] -> [a]
topo suc vs = fst $ foldl' visit ([], []) vs where
  visit (done, doing) v
    | v `elem` done || v `elem` doing = (done, doing)
    | otherwise = (\(xs, x:ys) -> (x:xs, ys)) $
      foldl' visit (done, v:doing) (suc v)

freeVars :: Ast -> AAst [String]
freeVars (Ast ast) = g [] ast where
  g :: [String] -> AstF Ast -> AAst [String]
  g cand (Lam ss (Ast a)) = AAst (vs \\ ss) $ Lam ss a1 where
    a1@(AAst vs _) = g (union cand ss) a
  g cand (Ast x :@ Ast y) = AAst (xv `union` yv) $ x1 :@ y1 where
    x1@(AAst xv _) = g cand x
    y1@(AAst yv _) = g cand y
  g cand (Var v) | v `elem` cand = AAst [v] $ Var v
                 | otherwise     = AAst []  $ Var v
  g cand (Cas (Ast x) as) = AAst (foldl' union xv $ fst <$> as1) $ Cas x1 $ snd <$> as1 where
    x1@(AAst xv _) = g cand x
    as1 = map h as
    h (Ast p, Ast e) = (vs1, (g [] p, e1)) where
      e1@(AAst vs _) = g (cand `union` caseVars p) e
      vs1 = vs \\ caseVars p
  g cand (Let ds (Ast e)) = AAst (ev \\ binders) $ Let ds1 e1 where
    e1@(AAst ev _) = g (cand `union` binders) e
    binders = fst <$> ds
    ds1 = map h ds
    h (s, Ast x) = (s, g (cand `union` binders) x)
  g _ x = ffix (\h (Ast a) -> AAst [] $ h a) $ Ast x

caseVars :: AstF Ast -> [String]
caseVars (Var v) = [v]
caseVars (Ast x :@ Ast y) = caseVars x `union` caseVars y
caseVars _ = []

saturateCons :: Ast -> Ast
saturateCons = ffix $ \h ast -> let
  (t:spine) = spinal [] ast
  in case t of
    Pack m n | n > length spine -> Ast $ Lam vars body where
      vars = show <$> [1..n - length spine]
      aVars = Ast . Var <$> vars
      body = foldl' ((Ast .) . (:@)) (Ast $ Pack m n) $ (++ aVars) $ getRs spine
    _ -> foldl' ((Ast .) . (:@)) (Ast $ h t) $ getRs spine
  where
  spinal sp (Ast ast) = case ast of
    (l :@ _) -> spinal (ast:sp) l
    _ -> ast:sp
  getRs = map (saturateCons . (\(_ :@ r) -> r))

liftLambdas :: [(String, Ast)] -> [(String, Ast)]
liftLambdas scs = existingDefs ++ newDefs where
  (existingDefs, (_, newDefs)) = runState (mapM f $ second freeVars <$> scs) ([], [])
  f (s, AAst _ (Lam args body)) = do
    modify $ first $ const [s]
    body1 <- g body
    pure (s, Ast $ Lam args body1)
  f _ = error "bad top-level definition"
  genName :: State ([String], [(String, Ast)]) String
  genName = do
    (names, ys) <- get
    let
      n = head $ filter (`notElem` names) $
        (++ ('$':last names)) . show <$> [(0::Int)..]
    put (n:names, ys)
    pure n
  g :: AAst [String] -> State ([String], [(String, Ast)]) Ast
  g = bifix mapM $ \h (AAst fvs ast) -> case ast of
    Let ds t -> fmap Ast $ Let <$> mapM noLamb ds <*> g t where
      noLamb (name, AAst dfvs (Lam ss body)) = do
        n <- genName
        body1 <- g body
        modify $ second ((n, Ast $ Lam (dfvs ++ ss) body1):)
        pure (name, foldl' ((Ast .) . (:@)) (Ast $ Var n) $ Ast . Var <$> dfvs)
      noLamb (name, a) = (,) name <$> g a
    lam@(Lam _ _) -> do
      n <- genName
      g $ AAst fvs $ Let [(n, AAst fvs lam)] (AAst [n] $ Var n)
    _ -> Ast <$> h ast

expandCase :: Ast -> Ast
expandCase = ffix $ \h (Ast ast) -> Ast $ case ast of
  Cas e alts -> dupCase (rec e) alts
  _ -> h ast
  where
    rec = expandCase
    dupCase e [a] = Cas e $ evalState (expandAlt Nothing [] a) 0
    dupCase e (a:as) = Cas e $ evalState (expandAlt (Just $ rec $ Ast $ Cas e as) [] a) 0
    dupCase _ _ = error "BUG! no case alternatives"

    -- TODO: Call `fromApList` only in last case alternative.
    expandAlt :: Maybe Ast -> [(Ast, Ast)] -> (Ast, Ast) -> State Int [(Ast, Ast)]
    expandAlt onFail deeper (p, a) = case fromApList p of
      [Ast (Var _)] -> (:moreCases) . (,) p <$> g deeper a
      [Ast (S s)] -> do
        v <- genVar
        a1 <- g deeper a
        pure [(Ast $ Var v, Ast $ Cas (Ast (Ast (Ast (Var "eq_String") :@ Ast (Var v)) :@ Ast (S s))) $ (Ast $ Pack 1 0, a1):moreCases)]
      [Ast (I n)] -> do
        v <- genVar
        a1 <- g deeper a
        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)]
      h@(Ast (Pack _ _)):xs -> (++ moreCases) <$> doPack [h] deeper xs a
      _ -> error $ "bad case: " ++ show p

      where
      moreCases = maybe [] (pure . (,) (Ast $ Var "_")) onFail
      doPack acc dpr [] body = (:moreCases) . (,) (foldl1 ((Ast .) . (:@)) acc) <$> g dpr body
      doPack acc dpr (h:rest) body = do
        gv <- Ast . Var <$> genVar
        case h of
          Ast (Var _) -> doPack (acc ++ [h]) dpr rest body
          _ -> doPack (acc ++ [gv]) (dpr ++ [(gv, h)]) rest body
      g [] body = pure body
      g ((v, w):rest) body = fmap Ast $ Cas v <$> expandAlt onFail rest (w, body)

    genVar = do
      n <- get
      put (n + 1)
      pure $ "c*" ++ show n

    fromApList :: Ast -> [Ast]
    fromApList (Ast (a :@ b)) = fromApList a ++ [b]
    fromApList a = [a]

messageTypes :: [String]
messageTypes = ["Databuf", "String", "Actor", "Module", "Port", "I32", "Int", "Bool", "()"]


================================================
FILE: src/Encode.hs
================================================
{-# LANGUAGE CPP #-}
module Encode
  ( encodeWasm
  , ProtoWasm(..)
  , leb128
  , sleb128
  , enc32
  , encType
  , WasmFun(..)
  ) where

import Control.Arrow
#ifdef __HASTE__
import qualified Data.Set as IS
import qualified Data.Map.Strict as IM
#else
import Data.IntMap.Strict (restrictKeys)
import qualified Data.IntSet as IS
import qualified Data.IntMap.Strict as IM
#endif
import Data.Bits
import Data.Char
import Data.List
import WasmOp

#ifdef __HASTE__
type IntMap = IM.Map Int
type IntSet = IS.Set Int
restrictKeys :: IntMap a -> IntSet -> IntMap a
restrictKeys m s = IM.filterWithKey (\k _ -> IS.member k s) m
#endif

type FuncType = ([WasmType], [WasmType])

wasmHeader :: [Int]
wasmHeader = [0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]  -- Magic string, version.

encWasmOp :: (FuncType -> Int) -> WasmOp -> [Int]
encWasmOp findSig op = case op of
  Get_local n -> 0x20 : leb128 n
  Set_local n -> 0x21 : leb128 n
  Tee_local n -> 0x22 : leb128 n
  Get_global n -> 0x23 : leb128 n
  Set_global n -> 0x24 : leb128 n
  I64_const n -> 0x42 : sleb128 n
  I32_const n -> 0x41 : sleb128 n
  Call n -> 0x10 : leb128 n
  Call_indirect sig -> 0x11 : leb128 (findSig sig) ++ [0]
  I64_load m n -> [0x29, m, n]
  I64_store m n -> [0x37, m, n]
  I32_load m n -> [0x28, m, n]
  I32_load8_u m n -> [0x2d, m, n]
  I32_load16_u m n -> [0x2f, m, n]
  I32_store m n -> [0x36, m, n]
  I32_store8 m n -> [0x3a, m, n]
  Br n -> 0xc : leb128 n
  Br_if n -> 0xd : leb128 n
  Br_table bs a -> 0xe : leb128 (length bs) ++ concatMap leb128 (bs ++ [a])
  If t as [] -> [0x4, encType t] ++ concatMap rec as ++ [0xb]
  If t as bs -> concat
    [ [0x4, encType t]
    , concatMap rec as
    , [0x5]
    , concatMap rec bs
    , [0xb]
    ]
  Block t as -> [2, encType t] ++ concatMap rec as ++ [0xb]
  Loop t as -> [3, encType t] ++ concatMap rec as ++ [0xb]
  _ -> maybe (error $ "unsupported: " ++ show op) pure $ lookup op rZeroOps
  where rec = encWasmOp findSig

enc32 :: Int -> [Int]
enc32 n = (`mod` 256) . div n . (256^) <$> [(0 :: Int)..3]

encMartinType :: WasmType -> Int
encMartinType t = case t of
  Ref "Actor" -> 0x6f
  Ref "Module" -> 0x6e
  Ref "Port" -> 0x6d
  Ref "Databuf" -> 0x6c
  Ref "Elem" -> 0x6b
  _ -> encType t

encType :: WasmType -> Int
encType t = case t of
  I32 -> 0x7f
  I64 -> 0x7e
  F32 -> 0x7d
  F64 -> 0x7c
  AnyFunc -> 0x70
  Nada -> 0x40
  _ -> error $ "bad type:" ++ show t

standardSig :: FuncType -> FuncType
standardSig (a, b) = (standardType <$> a, standardType <$> b)

standardType :: WasmType -> WasmType
standardType t = case t of
  Ref _ -> I32
  _ -> t

leb128 :: Int -> [Int]
leb128 n | n < 128   = [n]
         | otherwise = 128 + (n `mod` 128) : leb128 (n `div` 128)

sleb128 :: (Bits a, Integral a) => a -> [Int]
sleb128 n | n < 0     = fromIntegral <$> f (n .&. 127) (shiftR n 7)
          | n < 64    = [fromIntegral n]
          | n < 128   = [128 + fromIntegral n, 0]
          | otherwise = 128 + (fromIntegral n `mod` 128) : sleb128 (n `div` 128)
          where
          f x (-1) | x < 64    = [x .|. 128, 127]
                   | otherwise = [x]
          f x y    = (x .|. 128):f (y .&. 127) (shiftR y 7)

encCustom :: String -> [[Int]] -> [Int]
encCustom s xs = 0 : lenc (encStr s ++ varlen xs ++ concat xs)

encStr :: String -> [Int]
encStr s = lenc $ ord <$> s

varlen :: [a] -> [Int]
varlen xs = leb128 $ length xs

lenc :: [Int] -> [Int]
lenc xs = varlen xs ++ xs

data ProtoWasm = ProtoWasm
  { sectImports :: [((String, String), FuncType)]
  , sectFunctions :: [WasmFun]
  , tableSize :: Int
  , sectGlobals :: [[Int]]
  , sectExports :: [(String, Int)]
  , sectElements :: [(Int, [Int])]
  , sectPersist :: [(Int, WasmType)]
  , sectDfn :: [(Int, [WasmType])]
  , sectsCustom :: [(String, [[Int]])]
  , sectsGeneric :: [(Int, [[Int]])]
  }

encodeWasm :: ProtoWasm -> [Int]
encodeWasm fatP = concat
  [ wasmHeader
  -- Custom sections using Martin's annotations.
  , encCustom "types" $ encMartinTypes . snd <$> sectDfn p
  -- Martin subtracts the number of imports from the function index.
  , encCustom "typeMap" $ zipWith (++) (leb128 . (+(-length (sectImports p))) . fst <$> sectDfn p) $ leb128 <$> [0..]
  -- Encodes persistent globals.
  , encCustom "persist" . fmap encMartinGlobal . sortOn fst $ sectPersist p
  , encSect 1 $ encSig <$> sigs  -- Type section.
  , encSect 2 $ importFun <$> sectImports p  -- Import section.
  , encSect 3 $ pure . findSig . typeSig <$> sectFunctions p  -- Function section.
  -- Table section.
  -- Selects "no-maximum" (0).
  , if tableSize p == 0 then [] else encSect 4 [[encType AnyFunc, 0] ++ leb128 (tableSize p)]
  , concat $ getSect 5
  , encSect 6 $ sectGlobals p  -- Global section.
  , encSect 7 $  -- Export section.
    -- The "public" functions.
    [encStr s ++ (0 : leb128 n) | (s, n) <- sectExports p] ++
    [ encStr "memory" ++ [2, 0]  -- 2 = external_kind Memory, 0 = memory index.
    , encStr "table" ++ [1, 0]  -- 1 = external_kind Table, 0 = memory index.
    ]
  -- Export all globals. Forbidden by the spec, but our engine can handle it.
#ifndef __HASTE__
    ++ [ encStr ("global" ++ show n) ++ (3:leb128 n) | n <- [0..length (sectGlobals p) - 1]]
#endif
  , concat $ getSect 8
  -- Element section.
  , if null $ sectElements p then [] else
    encSect 9 $ encTableChunk <$> sectElements p
  , encSect 10 $ encProcedure <$> sectFunctions p
  , concat $ getSect 11
  , concatMap (uncurry encCustom) $ sectsCustom p
  ]
  where
  p = trim fatP
  encTableChunk (offset, entries) =
    [ 0  -- Table 0 (only one in MVP).
    , 0x41] ++ leb128 offset ++ [0xb]
    ++ leb128 (length entries)
    ++ concatMap leb128 entries
  getSect k
    | Just ns <- lookup k $ sectsGeneric p = [encSect k ns]
    | otherwise = []
  sigs = nub $ fmap standardSig $
    (snd <$> sectImports p) ++  -- Types of imports.
    (typeSig <$> sectFunctions p) ++  -- Types of functions.
    concatMap (concatMap ciType . funBody) (sectFunctions p) -- Types of Call_indirect types.
  ciType (Call_indirect t) = [t]
  ciType (Block _ xs) = concatMap ciType xs
  ciType (Loop _ xs) = concatMap ciType xs
  ciType (If _ xs ys) = concatMap ciType $ xs ++ ys
  ciType _ = []
  encSig (ins, outs) = 0x60 : lenc (encType <$> ins) ++ lenc (encType <$> outs)
  findSig :: FuncType -> Int
  findSig sig
    | Just n <- sigIndex = n
    | otherwise = error $ "BUG! missing sig in type section: " ++ show sig
    where sigIndex = elemIndex (standardSig sig) sigs
  importFun ((m, f), ty) = encStr m ++ encStr f ++ [0, findSig ty]
  encMartinTypes ts = 0x60 : lenc (encMartinType <$> ts) ++ [0]
  encMartinGlobal (i, t) = [3] ++ leb128 i ++ leb128 (encMartinType t)
  encProcedure wf = lenc $ leb128 (length $ localVars wf) ++
    concatMap (\t -> [1, encType $ standardType t]) (localVars wf) ++
    concatMap (encWasmOp findSig) (funBody wf)
  encSect t xs = t : lenc (varlen xs ++ concat xs)

-- Trim unreachable wasm code.
trim :: ProtoWasm -> ProtoWasm
trim p = p
  { sectImports = liveImps
  , sectFunctions = IM.elems liveFuns
  , sectExports = second (liveRenames IM.!) <$> sectExports p
  , sectElements = filter (not . null . snd) $ second (map (liveRenames IM.!)) <$> sectElements p
  , sectDfn = first (liveRenames IM.!) <$> sectDfn p
  }
  where
  nonImports = IM.fromList $ zip [length $ sectImports p..] $ sectFunctions p
  liveCalls = followCalls ((snd <$> sectExports p) `union` concatMap snd (sectElements p)) $ funBody <$> nonImports
  liveRenames = IM.fromList $ zip (IS.elems liveCalls) [0..]
  liveImps = map snd $ filter ((`IM.member` liveRenames) . fst) $ zip [0..] $ sectImports p
  liveFuns = (\wf -> wf { funBody = renumberCalls liveRenames $ funBody wf }) <$> restrictKeys nonImports (IM.keysSet liveRenames)


================================================
FILE: src/Hero/.gitignore
================================================
.DS_Store
.stack-work*


================================================
FILE: src/Hero/Hero.hs
================================================
{-# LANGUAGE CPP #-}
{-# LANGUAGE NamedFieldPuns #-}

module Hero.Hero
  ( Wasm(dfnExports, haskell)
  , CustomWasmOp(I32_const, I64_const), WasmOp
  , Hero
  , parseWasm
  , invoke
  , decode
  , setSlot
  , globals
  , getMemory, putMemory
  , getExport
  , getSlot
  , ripWasm
  ) where

#ifdef __HASTE__
import qualified Data.Map.Strict as IM
#else
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
#endif
import Data.Bits
import Data.Int
import Data.List
import Data.Maybe
import Data.Word

import Hero.Parse
import WasmOp

#ifdef __HASTE__
type IntMap = IM.Map Int
#endif

type VMFun m a = [WasmOp] -> (a, Hero) -> m ([WasmOp], (a, Hero))
-- | The import functions and table functions.
type VMEnv m a = ((String, String) -> VMFun m a, Int -> VMFun m a)

data Hero = Hero
  { globs :: IntMap WasmOp
  , locs  :: [IntMap WasmOp]
  , stack :: [WasmOp]
  , insts :: [[WasmOp]]
  , mem   :: IntMap Word8
  , sigs  :: IntMap ([WasmType], [WasmType])
  , table :: IntMap (Either Int Int)
  , wasm  :: Wasm
  }

-- | Reads global variables.
globals :: Hero -> [(Int, WasmOp)]
globals vm = IM.assocs $ globs vm

-- | Reads a byte from memory.
getMemory :: Int32 -> Hero -> Word8
getMemory a vm = getWord8 a $ mem vm

-- | Writes a byte to memory.
putMemory :: Int32 -> Word8 -> Hero -> Hero
putMemory a n vm = vm { mem = putWord8 a n $ mem vm }

getWord8 :: Int32 -> IntMap Word8 -> Word8
getWord8 a mem = fromMaybe 0 $ IM.lookup (fromIntegral a) mem

putWord8 :: Int32 -> Word8 -> IntMap Word8 -> IntMap Word8
putWord8 a n mem = IM.insert (fromIntegral a) n mem

getNum :: Integral n => Int -> Int32 -> IntMap Word8 -> n
getNum w addr mem = sum $ zipWith (*) bs ((256^) <$> [(0 :: Int)..]) where
  bs = fromIntegral . (`getWord8` mem) . (addr +) <$> [0..fromIntegral w-1]

putNum :: Integral n => Int -> Int32 -> n -> IntMap Word8 -> IntMap Word8
putNum w addr n mem = foldl' f mem [0..w-1] where
  f m k = putWord8 (addr + fromIntegral k) (getByte k) m
  getByte k = fromIntegral $ ((fromIntegral n :: Word64) `shiftR` (8*k)) .&. 255

rotateL32 :: Word32 -> Word32 -> Word32
rotateL32 a b = rotateL a $ fromIntegral (b `mod` 32)

rotateR32 :: Word32 -> Word32 -> Word32
rotateR32 a b = rotateR a $ fromIntegral (b `mod` 32)

shiftL32 :: Word32 -> Word32 -> Word32
shiftL32 a b = shiftL a $ fromIntegral (b `mod` 32)

shiftR32U :: Word32 -> Word32 -> Word32
shiftR32U a b = shiftR a $ fromIntegral (b `mod` 32)

shiftR32S :: Int32 -> Int32 -> Int32
shiftR32S a b = shiftR a $ fromIntegral (b `mod` 32)

shiftR64U :: Int64 -> Int64 -> Int64
shiftR64U a b = fromIntegral $ shiftR ((fromIntegral a) :: Word64) $ fromIntegral ((fromIntegral b :: Word64) `mod` 64)

shiftR64S :: Int64 -> Int64 -> Int64
shiftR64S a b = fromIntegral $ shiftR ((fromIntegral a) :: Int64) $ fromIntegral ((fromIntegral b :: Int64) `mod` 64)

shiftL64 :: Int64 -> Int64 -> Int64
shiftL64 a b = shiftL a $ fromIntegral ((fromIntegral b :: Word64) `mod` 64)

rotateR64 :: Int64 -> Int64 -> Int64
rotateR64 a b = rotateR a $ fromIntegral ((fromIntegral b :: Word64) `mod` 64)

drop' :: Int -> [a] -> [a]
drop' n as | n > length as = error "BAD DROP"
           | otherwise = drop n as

take' :: Int -> [a] -> [a]
take' n as | n > length as = error "BAD TAKE"
           | otherwise = take n as

initLocal :: WasmType -> WasmOp
initLocal I32 = I32_const 0
initLocal I64 = I64_const 0
initLocal _ = error "TODO"

runImps :: Monad m => VMEnv m a -> (a, Hero) -> m ([WasmOp], (a, Hero))
runImps (imps, tabs) (st0, engine) = run st0 engine where
  run st vm@Hero {insts, stack}
    | null insts = pure (stack, (st, vm))
    | null $ head insts = case tail insts of
      ((Loop _ _:rest):t) -> run st vm {insts = rest:t}
      _                   -> run st vm {insts = tail insts}
  run st vm@Hero{globs, locs, stack, insts, mem} = case head $ head insts of
    Call_indirect (inSig, _) -> do
      let
        -- TODO: Dynamic type-check.
        inCount = length inSig
        (I32_const i:params) = take' (inCount + 1) stack
      (results, (a, vm1)) <- case table vm IM.! fromIntegral i of
        Left n -> run st vm { insts = (Call n:head insts):tail insts }
        Right n -> tabs n (reverse params) (st, step $ drop' (inCount + 1) stack)
      run a $ setArgsVM results vm1
    Call i -> let
      Wasm {imports, functions} = wasm vm
      fCount = length imports
      in if i < fCount then do
        let
          (importName, (ins, _)) = imports!!i
          k = length ins
        (results, (a, vm1)) <- imps importName (reverse $ take' k stack) (st, step $ drop' k stack)
        run a $ setArgsVM results vm1
      else do
        let
          WasmFun {typeSig, localVars, funBody} = functions IM.! i
          locals = initLocal <$> localVars
          k = length $ fst typeSig
        -- The `End` opcode is reintroduced at the ends of function calls, so
        -- we know when to pop locals, and when to stop popping instructions
        -- for `Return`.
        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 }
    Return -> run st vm { insts = dropWhile ((End /=) . head) insts }
    End -> run st vm { locs = tail locs, insts = i1 }
    Set_local i -> run st vm {locs = IM.insert i (head stack) (head locs):tail locs, stack = tail stack, insts = i1}
    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
    Tee_local i -> run st vm {locs = IM.insert i (head stack) (head locs):tail locs, insts = i1}
    Set_global i -> run st vm {globs = IM.insert i (head stack) globs, stack = tail stack, insts = i1}
    Get_global i -> if i >= IM.size globs then error $ "BUG! bad global: " ++ show (i, globs)
      else run st $ step $ globs IM.! i:stack
    c@(I32_const _) -> run st $ step $ c:stack
    c@(I64_const _) -> run st $ step $ c:stack
    I32_xor -> binOp32 xor
    I32_and -> binOp32 (.&.)
    I32_or -> binOp32 (.|.)
    I32_add -> binOp32 (+)
    I32_sub -> binOp32 (-)
    I32_mul -> binOp32 (*)
    I32_div_s -> binOp32 div
    I32_div_u -> binOp32U div
    I32_rem_s -> binOp32 rem
    I32_rem_u -> binOp32U rem
    I32_shl -> binOp32U shiftL32
    I32_rotl -> binOp32U rotateL32
    I32_rotr -> binOp32U rotateR32
    I32_shr_u -> binOp32U shiftR32U
    I32_shr_s -> binOp32 shiftR32S
    I32_ge_s -> binOp32 $ ((fromIntegral . fromEnum) .) . (>=)
    I32_gt_s -> binOp32 $ ((fromIntegral . fromEnum) .) . (>)
    I32_le_s -> binOp32 $ ((fromIntegral . fromEnum) .) . (<=)
    I32_lt_s -> binOp32 $ ((fromIntegral . fromEnum) .) . (<)
    I32_gt_u -> binOp32U $ (fromEnum .) . (>)
    I32_ge_u -> binOp32U $ (fromEnum .) . (>=)
    I32_lt_u -> binOp32U $ (fromEnum .) . (<)
    I32_le_u -> binOp32U $ (fromEnum .) . (<=)
    I32_ne -> binOp32 $ ((fromIntegral . fromEnum) .) . (/=)
    I32_eq -> binOp32 $ ((fromIntegral . fromEnum) .) . (==)
    I32_eqz -> let
      (I32_const a:t) = stack
      in run st $ step $ (I32_const $ fromIntegral $ fromEnum $ a == 0):t
    I64_le_s -> boolBinOp64 (<=)
    I64_lt_s -> boolBinOp64 (<)
    I64_ge_s -> boolBinOp64 (>=)
    I64_gt_s -> boolBinOp64 (>)
    I64_le_u -> boolBinOp64U (<=)
    I64_lt_u -> boolBinOp64U (<)
    I64_ge_u -> boolBinOp64U (>=)
    I64_gt_u -> boolBinOp64U (>)
    I64_eq -> boolBinOp64 (==)
    I64_add -> binOp64 (+)
    I64_sub -> binOp64 (-)
    I64_mul -> binOp64 (*)
    I64_div_s -> binOp64 div
    I64_div_u -> binOp64U div
    I64_xor -> binOp64 xor
    I64_and -> binOp64 (.&.)
    I64_or -> binOp64 (.|.)
    I64_rem_s -> binOp64 rem
    I64_rem_u -> binOp64U rem
    I64_shr_u -> binOp64 shiftR64U
    I64_shr_s -> binOp64 shiftR64S
    I64_shl -> binOp64 shiftL64
    I64_rotr -> binOp64 rotateR64
    I64_extend_s_i32 -> let
      I32_const a = head stack
      c = I64_const $ fromIntegral a
      in run st $ step (c:tail stack)
    I64_extend_u_i32 -> let
      I32_const a = head stack
      c = I64_const $ fromIntegral (fromIntegral a :: Word32)
      in run st $ step (c:tail stack)
    I32_wrap_i64 -> let
      I64_const a = head stack
      c = I32_const $ fromIntegral a
      in run st $ step (c:tail stack)
    I32_load8_u  _ o -> load32 1 o
    I32_load16_u _ o -> load32 2 o
    I32_load     _ o -> load32 4 o
    I32_store8   _ o -> store32 1 o
    I32_store16  _ o -> store32 2 o
    I32_store    _ o -> store32 4 o
    I64_store _ o -> do
      let
        I32_const addr = stack!!1
        I64_const n = head stack
      let mem' = putNum 8 (addr + fromIntegral o) n mem
      run st (step $ drop 2 stack) { mem = mem'}
    I64_load _ o -> do
      let I32_const addr = head stack
          c = I64_const $ getNum 8 (addr + fromIntegral o) mem
      run st $ step (c:tail stack)

    If _ t f -> let I32_const n = head stack in if n /= 0
      then run st vm {stack = tail stack, insts = t:i1}
      else run st vm {stack = tail stack, insts = f:i1}
    Block _ bl -> run st vm {insts = bl:i1}
    Loop _ bl -> run st vm {insts = bl:insts}
    Br k -> run st vm {insts = drop (k + 1) insts}
    Br_if k -> let (I32_const n:t) = stack in if n /= 0
      then run st vm {stack = t, insts = drop (k + 1) insts}
      else run st vm {stack = t, insts = i1}
    Br_table as d -> do
      let
        n = fromIntegral n' where I32_const n' = head stack
        k = if n < 0 || n >= length as then d else as!!n
      run st vm {stack = tail stack, insts = drop (k + 1) insts}
    Unreachable -> pure ([], (st, vm))
    Drop -> run st $ step $ tail stack
    Select -> do
      let
        [I32_const c, f, t] = take' 3 stack
        r = if c /= 0 then t else f
      run st $ step $ r:drop 3 stack
    _ -> error $ "TODO: " ++ show (head $ head insts)
    where
    step newStack = vmNext { stack = newStack }
    vmNext = vm { insts = i1 }
    i1 = tail (head insts):tail insts
    binOp32 f = run st $ step (c:drop 2 stack) where
      (I32_const b:I32_const a:_) = stack
      c = I32_const $ f a b
    binOp32U f = run st $ step (c:drop 2 stack) where
      (I32_const b:I32_const a:_) = stack
      c = I32_const $ fromIntegral $ f (toU32 a) (toU32 b) where
        toU32 n = (fromIntegral n :: Word32)
    binOp64 f = run st $ step (c:drop 2 stack) where
      (I64_const b:I64_const a:_) = stack
      c = I64_const $ f a b
    binOp64U f = run st $ step (c:drop 2 stack) where
      (I64_const b:I64_const a:_) = stack
      c = I64_const $ fromIntegral $ f (toU64 a) (toU64 b)
    boolBinOp64 f = run st $ step (c:drop 2 stack) where
      (I64_const b:I64_const a:_) = stack
      c = I32_const $ fromIntegral $ fromEnum $ f a b
    boolBinOp64U f = run st $ step (c:drop 2 stack) where
      (I64_const b:I64_const a:_) = stack
      c = I32_const $ fromIntegral $ fromEnum $ f (toU64 a) (toU64 b)
    load32 sz off = run st $ step (I32_const (getNum sz (addr + fromIntegral off) mem):tail stack)
      where I32_const addr = head stack
    toU64 x = fromIntegral x :: Word64
    store32 sz off = do
      let (I32_const n:I32_const addr:_) = stack
          mem' = putNum sz (addr + fromIntegral off) n mem
      run st (step $ drop 2 stack) { mem = mem'}

-- | Returns an exported function.
getExport :: String -> Hero -> Int
getExport f vm =
  fromMaybe (error $ "bad export: " ++ f) $ lookup f $ exports $ wasm vm

-- | Returns a function initially in the table.
getSlot :: Int32 -> Hero -> Int
getSlot i vm = either id (error $ "must be called before invoke") $
  fromMaybe (error $ "bad slot: " ++ show i) $
  IM.lookup (fromIntegral i) $ table vm

-- | Interprets a wasm function.
invoke :: Monad m => VMEnv m a -> [(Int, WasmOp)] -> Int -> [WasmOp] -> (a, Hero) -> m ([WasmOp], (a, Hero))
invoke env gs k args (st, vm0) =
  runImps env (st, (setArgsVM args vm) { insts = [[Call k]] })
  where
  Wasm{globalSection, dataSection, elemSection} = wasm vm0
  vm = vm0
    { locs = []
    , stack = []
    , globs = IM.fromList $ zip [0..] (head . snd <$> globalSection) ++ gs
    , mem = IM.fromList $ concatMap strToAssocs dataSection
    , table = IM.fromList $ concatMap mkElems elemSection
    }
  strToAssocs ([I32_const n], s) = zip [fromIntegral n..] $ fromIntegral <$> s
  strToAssocs _ = error "BUG!"

mkElems :: (Int, [Int]) -> [(Int, Either Int Int)]
mkElems (offset, ns) = zip [offset..] $ Left <$> ns

-- | Builds a Hero from imports and wasm binary.
decode :: Wasm -> Hero
decode w@Wasm{elemSection, types} = Hero
  { locs = undefined
  , stack = undefined
  , insts = undefined
  , globs = undefined
  , mem = undefined
  , table = IM.fromList $ concatMap mkElems elemSection
  , sigs = IM.fromList $ zip [0..] types
  , wasm = w
  }

-- | Place arguments on WebAssembly stack.
setArgsVM :: [WasmOp] -> Hero -> Hero
setArgsVM ls vm = vm { stack = reverse ls ++ stack vm }

-- TODO: Check slot is in range.
setSlot :: Int32 -> Int -> Hero -> Hero
setSlot slot k vm = vm
  { table = IM.insert (fromIntegral slot) (Right k) $ table vm }


================================================
FILE: src/Hero/HeroIO.hs
================================================
-- HeroIO is a wasm engine with a more natural interface for setting
-- table entries to IO functions.
--
-- On principle, I'd like to keep a pure wasm engine,
-- which is why HeroIO is distinct from Hero.

module Hero.HeroIO
  ( HeroIO
  , decode
  , invoke
  , getMemory
  , putMemory
  , getSlot
  , setSlot
  , getExport
  , globals
  ) where

import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.Word (Word8)
import Hero.Hero (Hero)
import qualified Hero.Hero as Hero
import WasmOp

newtype HeroAux = HeroAux { heroAux :: [WasmOp] -> HeroIO -> IO ([WasmOp], HeroIO) }

type HeroIO = (((String, String) -> HeroAux, IntMap HeroAux), Hero)

decode :: ((String, String) -> [WasmOp] -> HeroIO -> IO ([WasmOp], HeroIO)) -> Hero.Wasm -> HeroIO
decode imps w = ((HeroAux . imps, IM.empty), Hero.decode w)

getMemory :: Int32 -> HeroIO -> Word8
getMemory k (_, h) = Hero.getMemory k h

putMemory :: Int32 -> Word8 -> HeroIO -> HeroIO
putMemory k v (x, h) = (x, Hero.putMemory k v h)

getSlot :: Int32 -> HeroIO -> Int
getSlot k (_, h) = Hero.getSlot k h

getExport :: String -> HeroIO -> Int
getExport k (_, h) = Hero.getExport k h

globals :: HeroIO -> [(Int, WasmOp)]
globals (_, h) = Hero.globals h

setSlot :: Int32 -> ([WasmOp] -> HeroIO -> IO ([WasmOp], HeroIO)) -> HeroIO -> HeroIO
setSlot n f ((imps, x), vm) = ((imps, IM.insert k (HeroAux f) x), Hero.setSlot n k vm)
  where k = IM.size x

invoke
  :: [(Int, WasmOp)]  -- Globals.
  -> Int              -- Function.
  -> [WasmOp]         -- Arguments.
  -> HeroIO           -- VM.
  -> IO ([WasmOp], HeroIO)
invoke gs f as h = Hero.invoke (heroAux . fst (fst h), resolve) gs f as h

resolve :: Int -> [WasmOp] -> HeroIO -> IO ([WasmOp], HeroIO)
resolve k args h = (heroAux $ snd (fst h) IM.! k) args h


================================================
FILE: src/Hero/Parse.hs
================================================
{-# LANGUAGE CPP #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}

module Hero.Parse (parseWasm, Wasm(..), ripWasm, elTable) where

#ifdef __HASTE__
import qualified Data.Map.Strict as IM
import qualified Data.Set as IS
#else
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.IntSet as IS
#endif
import Control.Arrow
import Control.Monad
import qualified Data.ByteString as B
import Data.ByteString (ByteString)
import Data.Char
import Data.Int
import Data.Maybe
import Data.Word
import WasmOp

#ifdef __HASTE__
type IntMap = IM.Map Int
#endif

data ExternalKind = Function | Table | Memory | Global
type FuncType = ([WasmType], [WasmType])

data Wasm = Wasm
  { types :: [FuncType]
  , imports :: [((String, String), FuncType)]
  , decls :: [FuncType]
  , tableSize :: Int
  , memory :: [(Int, Maybe Int)]
  , globalSection :: [((WasmType, Bool), [WasmOp])]
  , exports :: [(String, Int)]
  , start :: Maybe Int
  , elemSection :: [(Int, [Int])]
  , functions :: IntMap WasmFun
  , dataSection :: [([WasmOp], [Word8])]
  , dfnExports :: [(String, [WasmType])]
  , martinTypes :: [[WasmType]]
  , martinTypeMap :: [(Int, Int)]
  , permaGlobals :: [(Int, WasmType)]
  , persist :: [(Int, WasmType)]
  , haskell :: String
  } deriving Show

emptyWasm :: Wasm
emptyWasm = Wasm [] [] [] 0 [] [] [] Nothing [] IM.empty [] [] [] [] [] [] ""

data ByteParser a = ByteParser (ByteString -> Either String (a, ByteString))

instance Functor     ByteParser where fmap = liftM
instance Applicative ByteParser where {pure = return; (<*>) = ap}
instance Monad       ByteParser where
  ByteParser f >>= g = ByteParser $ (good =<<) . f
    where good (r, t) = let ByteParser gg = g r in gg t
  return a = ByteParser $ \s -> Right (a, s)

next :: ByteParser Word8
next = ByteParser f where
  f s | B.null s = Left "unexpected EOF"
      | otherwise = Right (B.head s, B.tail s)

repNext :: Int -> ByteParser ByteString
repNext n = ByteParser f where
  f s | B.length s < n = Left "missing bytes or size too large"
      | otherwise = Right $ B.splitAt n s

isEof :: ByteParser Bool
isEof = ByteParser f where f s = Right (B.null s, s)

bad :: String -> ByteParser a
bad = ByteParser . const . Left

byteParse :: ByteParser a -> ByteString -> Either String a
byteParse (ByteParser f) s = f s >>= (\(w, t) ->
  if B.null t then Right w else Left "expected EOF")

remainder :: ByteParser ByteString
remainder = ByteParser $ \s -> Right (s, "")

wasm :: ByteParser Wasm
wasm = do
  let
    rep getInt task = getInt >>= (`replicateM` task)

    varuint = fromIntegral <$> f 1 0 where
      f :: Integer -> Integer -> ByteParser Integer
      f m acc = do
        d <- fromIntegral <$> next
        if d > 127 then f (m * 128) $ (d - 128) * m + acc else pure $ d*m + acc

    varint = f 1 0 where
      f :: Integer -> Integer -> ByteParser Integer
      f m acc = do
        d <- fromIntegral <$> next
        if d > 127 then f (m * 128) $ (d - 128) * m + acc else pure $
          if d >= 64 then d*m + acc - 128*m else d*m + acc

    varuint1 = varuint
    varuint7 = next
    varuint32 = varuint

    varint7 :: ByteParser Int
    varint7 = do
      c <- fromIntegral <$> next
      when (c >= 128) $ error "bad varint7"
      pure $ if c >= 64 then c - 128 else c

    varint32 :: ByteParser Int32
    varint32 = fromIntegral <$> varint

    varint64 :: ByteParser Int64
    varint64 = fromIntegral <$> varint

    lstr :: ByteParser String
    lstr = rep varuint32 $ chr . fromIntegral <$> next

    allType = do
      t <- varuint7
      case lookup t [(0x7f, I32), (0x7e, I64), (0x7d, F32), (0x7c, F64), (0x70, AnyFunc), (0x60, Func), (0x40, Nada)] of
        Just ty -> pure ty
        Nothing -> bad $ "bad type: " ++ show t

    valueType = do
      t <- allType
      when (t `notElem` [I32, I64, F32, F64]) $ bad "bad value_type"
      pure t

    blockType = do
      t <- allType
      when (t `notElem` [I32, I64, F32, F64, Nada]) $ bad "bad value_type"
      pure t

    elemType = do
      t <- allType
      when (t /= AnyFunc) $ bad "bad elem_type"

    externalKind = do
      k <- varuint7
      pure $ case k of
        0 -> Function
        1 -> Table
        2 -> Memory
        3 -> Global
        _ -> error "bad external_kind"

    funcType = do
      form <- varint7
      when (form /= -32) $ bad "expected func type"
      paramTypes <- rep varuint32 valueType
      returnTypes <- rep varuint1 valueType
      pure (paramTypes, returnTypes)

    functionCount w = length (imports w) + length (decls w)

    sectType w = do
      t <- rep varuint32 funcType
      pure w { types = t }

    sectImport w = do
      ms <- rep varuint32 $ do
        moduleStr <- lstr
        fieldStr <- lstr
        k <- externalKind
        case k of
          Function -> do
            t <- varuint32
            when (t > length (types w)) $ bad "type out of range"
            pure ((moduleStr, fieldStr), types w !! t)
          _ -> error "TODO"
      pure w { imports = ms }

    sectExport w = do
      es <- rep varuint32 $ do
        fieldStr <- lstr
        k <- externalKind
        t <- varuint32
        case k of
          Function -> do
            when (t > functionCount w) $ bad "function index out of range"
            pure $ Just (fieldStr, t)
          Global -> pure Nothing
          Memory -> pure Nothing
          Table -> pure Nothing
      pure w { exports = catMaybes es }

    sectFunction w = do
      sigs <- rep varuint32 $ do
        t <- varuint32
        when (t > length (types w)) $ bad "type out of range"
        pure $ types w !! t
      pure w { decls = sigs }

    sectTable w = do
      n <- varuint32
      when (n > 1) $ bad "MVP allows at most one table"
      if n == 0 then pure w else do
        elemType
        flags <- varuint1
        m <- varuint32
        when (flags == 1) $ void varuint32  -- TODO: Record maximum.
        pure w { tableSize = m }

    sectMemory w = do
      n <- varuint32
      when (n > 1) $ bad "MVP allows at most one memory"
      if n == 0 then pure w else do
        flags <- varuint1
        initial <- varuint32
        if flags > 0 then do
          m <- varuint32
          pure w { memory = [(initial, Just m)] }
        else pure w { memory = [(initial, Nothing)] }

    globalType = do
      ty <- valueType
      muta <- varuint1
      pure (ty, muta > 0)

    sectGlobal w = do
      gs <- rep varuint32 $ do
        gt <- globalType
        x <- codeBlock w
        pure (gt, x)
      pure w { globalSection = gs }

    sectStart w = do
      i <- varuint32
      when (i > functionCount w) $ bad "function index out of range"
      pure w { start = Just i }

    sectElement w = do
      es <- rep varuint32 $ do
        index <- varuint32
        when (index /= 0) $ bad "MVP allows at most one table"
        ~[I32_const offset] <- codeBlock w
        ns <- rep varuint32 $ do
          i <- varuint32
          when (i > functionCount w) $ bad "function index out of range"
          pure $ fromIntegral i
        pure (fromIntegral offset, ns)
      pure w { elemSection = es }

    sectCode w = do
      fs <- rep varuint32 $ do
        _ <- varuint32  -- Size.
        locals <- concat <$> rep varuint32 (replicate <$> varuint32 <*> valueType)
        ops <- codeBlock w
        pure (locals, ops)
      pure w { functions = IM.fromList $ zip [length (imports w)..]
        $ zipWith (\a (b, c) -> WasmFun a b c) (decls w) fs }

    sectData w = do
      ds <- rep varuint32 $ do
        index <- varuint32
        when (index /= 0) $ bad "MVP allows at most one memory"
        offset <- codeBlock w
        (,) offset <$> rep varuint32 next
      pure w { dataSection = ds }

    martinFuncType = do
      form <- varint7
      when (form /= -32) $ bad "expected func type"
      paramTypes <- rep varuint32 martinValueType
      z <- varuint1
      when (z /= 0) $ bad "must have no return value"
      pure paramTypes

    martinValueType = do
      t <- varuint7
      maybe (bad $ "bad type: " ++ show t) pure $ lookup t
        [ (0x7f, I32)
        , (0x7e, I64)
        , (0x7d, F32)
        , (0x7c, F64)
        , (0x70, Ref "Any")  -- AnyFunc in standard wasm.
        , (0x6f, Ref "Actor")
        , (0x6e, Ref "Module")
        , (0x6d, Ref "Port")
        , (0x6c, Ref "Databuf")
        , (0x6b, Ref "Elem")
        ]

    sectCustom w = do
      name <- lstr
      case name of
        "types" -> do
          t <- rep varuint32 martinFuncType
          pure w { martinTypes = t }
        "typeMap" -> do
          tm <- rep varuint32 $ (,) <$> varuint32 <*> varuint32
          pure w { martinTypeMap = tm }
        "persist" -> do
          g <- rep varuint32 $ do
            tmp <- varuint7
            when (tmp /= 3) $ bad "expect 3"
            (,) <$> varuint32 <*> martinValueType
          pure w { permaGlobals = g }
        "dfndbg" -> remainder >> pure w
        "dfnhs" -> do
          void $ varuint32  -- Should be 1.
          s <- remainder
          pure w { haskell = chr . fromIntegral <$> B.unpack s }
        _ -> remainder >> pure w

    codeBlock :: Wasm -> ByteParser [WasmOp]
    codeBlock w = do
      opcode <- fromIntegral <$> varuint7
      s <- if
        | Just s <- lookup opcode $ zeroOperandOps -> pure s
        | Just s <- lookup opcode [(0x02, Block), (0x03, Loop)] -> do
          bt <- blockType
          bl <- codeBlock w
          pure $ s bt bl
        | Just s <- lookup opcode [(0x20, Get_local), (0x21, Set_local), (0x22, Tee_local), (0x23, Get_global), (0x24, Set_global)] -> do
          v <- varuint32
          pure $ s v
        | 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
          flags <- varuint32
          offset <- varuint32
          pure $ s flags offset
        | Just s <- lookup opcode [(0x0c, Br), (0x0d, Br_if)] -> do
          v <- varuint32
          pure $ s v
        | otherwise -> case opcode of
          0x04 -> do
            bt <- blockType
            bl <- codeBlock w
            case last bl of
              Else -> do
                bl2 <- codeBlock w
                pure $ If bt (init bl) bl2
              _ -> pure $ If bt bl []
          0x05 -> pure Else
          0x0e -> do
            n <- varuint32
            tgts <- replicateM n varuint32
            defTgt <- varuint32
            pure $ Br_table tgts defTgt
          0x41 -> do
            i32 <- varint32
            pure $ I32_const i32
          0x42 -> do
            i64 <- varint64
            pure $ I64_const i64
          0x10 -> do
            i <- varuint32
            pure $ Call i
          0x11 -> do
            i <- varuint32
            ~ 0 <- varuint1
            when (i >= length (types w)) $ bad "Call_indirect index out of range"
            pure $ Call_indirect $ types w !! i
          _ -> bad ("bad opcode " ++ show opcode)
      if
        | Else <- s -> pure [Else]
        | End <- s -> pure []
        | otherwise -> (s:) <$> codeBlock w

    sect w = isEof >>= \b -> if b then pure w else do
      n <- varuint7
      m <- varuint32
      s <- repNext m
      let
        f = case n of
          1 -> sectType
          2 -> sectImport
          3 -> sectFunction
          4 -> sectTable
          5 -> sectMemory
          6 -> sectGlobal
          7 -> sectExport
          8 -> sectStart
          9 -> sectElement
          10 -> sectCode
          11 -> sectData
          0 -> sectCustom
          _ -> pure
      case byteParse (f w) s of
        Left err -> bad err
        Right w1 -> sect w1

  header <- repNext 8  -- Header and version.
  if header /= "\000asm\001\000\000\000" then
    bad "bad header or version"
  else sect emptyWasm  -- Sections.

parseWasm :: B.ByteString -> Either String Wasm
parseWasm b = do
  w@Wasm{imports, exports, martinTypeMap, martinTypes} <- byteParse wasm b
  let
    findType k
      | Just mt <- lookup (k - length imports) martinTypeMap = martinTypes!!mt
      -- Outputs make no sense for dfn, but we support them so we can use this
      -- code more generally.
      | k < length imports = fst $ snd $ imports !! k
      | otherwise = fst $ decls w !! (k - length imports)
  pure w { dfnExports = second findType <$> exports }

ripWasm :: [String] -> Wasm -> ([(String, Int)], [(Int, WasmFun)])
ripWasm es w = (zip es idxs, fMap)
  where
  Just idxs = mapM (`lookup` exports w) es
  reachable = IS.elems $ followCalls idxs $ funBody <$> functions w
  fMap = (\i -> (i, functions w IM.! i)) <$> reachable

-- Returns elements of table as
-- association list of slot to (function index, function type).
elTable :: Wasm -> [(Int, (Int, [WasmType]))]
elTable (Wasm {martinTypes, martinTypeMap, elemSection, imports})
  = second (\n -> (n, maybe (error "BUG! missing type")
    (martinTypes!!) $ lookup (n  - length imports) martinTypeMap)) <$> es where
  es = concatMap (\(offset, ns) -> zip [offset..] ns) elemSection


================================================
FILE: src/Hero/README.asciidoc
================================================
= The Hero Engine =

A WebAssembly interpreter.

Little verification is performed.

Only supports a subset of the specification.
In particular, there is no support for floating point operations.


================================================
FILE: src/Hero/default.nix
================================================
{ pkgs ? import  {}, compiler ? "ghc822" }:
with pkgs; let
  dhc = haskellPackages.callCabal2nix "dhc" ../dhc {};
  drv = haskellPackages.callCabal2nix "hero" ./. { inherit dhc; };
in if pkgs.lib.inNixShell 
  then stdenv.lib.overrideDerivation drv.env (oldAttrs : 
    {
      nativeBuildInputs = oldAttrs.nativeBuildInputs ++ [ cabal-install stack ];
    })
  else drv


================================================
FILE: src/Hero/hero.cabal
================================================
name:          hero
version:       0.0.0
synopsis:      WebAssembly interpreter.
license:       GPL-3
license-file:  LICENSE
copyright:     2017 DFINITY Stiftung
author:        Ben Lynn 
maintainer:    Ben Lynn 
stability:     Experimental
category:      Interpreter
homepage:      https://github.com/dfinity/hero
bug-reports:   https://github.com/dfinity/hero/issues
build-type:    Simple
cabal-version: >=1.10

library
  build-depends:
    base,
    bytestring,
    containers,
    dhc,
    parsec
  default-language:
    Haskell2010
  exposed-modules:
    Hero.Hero
    Hero.HeroIO
    Hero.Parse
  ghc-options:
    -O2
    -Wall


================================================
FILE: src/Hero/test/Main.hs
================================================
import qualified Data.ByteString as B
import Test.HUnit
import Hero.Hero
import Data.Functor.Identity

main :: IO Counts
main = runTestTT test42

test42 :: Test
test42 = TestCase $ assertEqual "i32.const 42" "42" =<< pure (runTiny fortyTwo)

runTiny :: B.ByteString -> String
runTiny asm = runIdentity $ fst . snd <$>
  invoke (syscall, undefined) [] (getExport "e" vm0) [] ("", vm0)
  where
  vm0 = decode $ either error id $ parseWasm asm
  syscall ("i", "f") [I32_const a] (s, vm) = pure ([], (s ++ show a, vm))
  syscall a b _ = error $ show ("BUG! bad syscall", a, b)

fortyTwo :: B.ByteString
-- Minimal wasm that exports a function returning the 32-bit integer 42.
-- See https://crypto.stanford.edu/~blynn/lambda/wasm.html
fortyTwo = B.pack
  [0,97,115,109,1,0,0,0,1,8,2,96,1,127,0,96,0,0,2,7,1,1,105,1
  ,102,0,0,3,2,1,1,7,5,1,1,101,0,1,10
  ,8  -- Length of code section.
  ,1
  ,6  -- Length of function.
  ,0
  -- If the following is changed, then the above lengths should match.
  ,65,42  -- 0x41, 42 means i32.const 42.
  ,16,0,11]


================================================
FILE: src/Hero/test/bm.hs
================================================
-- Benchmark parsing.
import Criterion.Main
import qualified Data.ByteString as B
import Hero.Parse
import WasmOp

main :: IO ()
main = do
  s <- B.getContents
  defaultMain $ pure $ bench "parse" $ (`whnf` s) $ functions . either error id . parseWasm


================================================
FILE: src/Parse.hs
================================================
{-# LANGUAGE CPP #-}
module Parse (parseDfnHs, lexOffside, TopLevel(..), QQuoter) where
#ifndef __HASTE__
import qualified Data.ByteString.Char8 as B
import Data.ByteString.Short (ShortByteString, toShort)
#endif
import Control.Arrow
import Control.Monad
import Data.Bool
import Data.List
import qualified Data.Map.Strict as M
import Data.Map.Strict (Map)
import Data.Maybe
import Text.Parsec
import Text.Parsec.Pos

import Ast

sbs :: String -> ShortByteString
#ifdef __HASTE__
sbs = id
type ShortByteString = String
#else
sbs = toShort . B.pack
#endif

type QQuoter = String -> String -> Either String String
data LexemeType = LexString | LexNumber | LexReserved | LexVar | LexCon | LexSpecial | LexVarSym | LexQual | IndError | IndCurly | IndAngle deriving (Eq, Show)
type Lexeme = (SourcePos, (LexemeType, String))
type Lexer = Parsec String QQuoter

reservedIds :: [String]
reservedIds = words "class data default deriving do else foreign if import in infix infixl infixr instance let module newtype of then type where _"

reservedOps :: [String]
reservedOps = ["..", "::", "=", "|", "<-", "->", "=>"]

rawTok :: Lexer Lexeme
rawTok = do
  pos <- getPosition
  r <- oxford <|> symbol <|> qId <|> num <|> special <|> str
  filler
  pure (pos, r)
  where
  lowId = do
    s <- (:) <$> (lower <|> char '_') <*> many (alphaNum <|> oneOf "_'")
    pure (if s `elem` reservedIds then LexReserved else LexVar, s)
  uppId = do
    s <- (:) <$> upper <*> many (alphaNum <|> oneOf "_'")
    pure (LexCon, s)
  qId = do
    r@(_, m) <- lowId <|> uppId
    try (do
      void $ char '.'
      (_, v) <- lowId <|> uppId
      pure (LexQual, m ++ '.':v)) <|> pure r
  num = do
    s <- many1 digit
    pure (LexNumber, s)
  special = (,) LexSpecial <$> foldl1' (<|>) (string . pure <$> "(),;[]`{}")
  symbol = do
    s <- many1 (oneOf "!#$%&*+./<=>?@\\^|-~:")
    pure (if s `elem` reservedOps then LexReserved else LexVarSym, s)
  str = do
    void $ char '"'
    s <- many $ (char '\\' >> escapes) <|> noneOf "\""
    void $ char '"'
    pure (LexString, s)
  escapes = foldl1' (<|>)
    [ char '\\' >> pure '\\'
    , char '"' >> pure '"'
    , char 'n' >> pure '\n'
    ]
  oxford = do
    q <- try $ between (char '[') (char '|') $ many alphaNum
    s <- oxfordClose <|> more
    qq <- getState
    case qq q s of
      Left err -> fail err
      Right out -> pure (LexString, out)
    where
    oxfordClose = try (string "|]") >> pure ""
    more = do
      s <- innerOxford <|> (pure <$> anyChar)
      (s ++) <$> (oxfordClose <|> more)
    innerOxford = do
      q <- try $ between (char '[') (char '|') $ many alphaNum
      s <- oxfordClose <|> more
      pure $ '[':q ++ ('|':s) ++ "|]"

filler :: Lexer ()
filler = void $ many $ void (char ' ') <|> nl <|> com
  where
  nl = (char '\r' >> optional (char '\n')) <|> void (oneOf "\n\f")
  com = void $ between (try $ string "--") nl $ many $ noneOf "\r\n\f"

-- We use the `sourceColumn` of Parsec's SourcePos to record indentation.
insertIndents :: [Lexeme] -> [Lexeme]
insertIndents [] = []
-- "If the first lexeme of a module is not { or module, then it is preceded by
-- {n} where n is the indentation of the lexeme."
insertIndents (x@(p, (LexSpecial, "{")):xs) = x:ii' (Just $ sourceLine p) xs
insertIndents xs@(h:_) = (fst h, (IndCurly, "")):ii' Nothing xs

ii' :: Maybe Line -> [Lexeme] -> [Lexeme]
ii' prevLine ls = case ls of
-- "If a let, where, do, or of keyword is not followed by the lexeme {, the
-- token {n} is inserted after the keyword, where n is the indentation of the
-- next lexeme if there is one, or 0 if the end of file has been reached."
  [] -> []
  [x]
    | lwdo x -> mayAngle x ++ [(newPos "" 0 0, (IndCurly, ""))]
    | otherwise -> mayAngle x
  (x@(p, _):y:rest)
    | lwdo x && not (isLBrace y) -> mayAngle x ++ (fst y, (IndCurly, "")):ii' Nothing (y:rest)
    | otherwise -> mayAngle x ++ ii' (Just $ sourceLine p) (y:rest)
-- "Where the start of a lexeme is preceded only by white space on the same
-- line, this lexeme is preceded by < n > where n is the indentation of the
-- lexeme, provided that it is not, as a consequence of the first two rules,
-- preceded by {n}."
  where
  mayAngle x@(p, _)
    | Just l <- prevLine, l /= sourceLine p = [(p, (IndAngle, "")), x]
    | otherwise = [x]
  lwdo (_, (LexReserved, s)) | s `elem` ["let", "where", "do", "of"] = True
  lwdo _ = False
  isLBrace (_, (LexSpecial, "{")) = True
  isLBrace _ = False

-- Handle layout. See the L function in:
--   https://www.haskell.org/onlinereport/haskell2010/haskellch10.html
algL :: [Lexeme] -> [Int] -> [Lexeme]
algL a@((p, (IndAngle, _)):ts) (m:ms)
  | m == n = insL p ";" $ algL ts (m:ms)
  | m >  n = insL p "}" $ algL a ms
  where n = sourceColumn p
algL ((_, (IndAngle, _)):ts) ms = algL ts ms
algL ((p, (IndCurly, _)):ts) (m:ms) | n > m = insL p "{" $ algL ts (n:m:ms)
  where n = sourceColumn p
algL ((p, (IndCurly, _)):ts) [] | n > 0 = insL p "{" $ algL ts [n]
  where n = sourceColumn p
algL ((p, (IndCurly, _)):ts) ms = insL p "{" $ insL p "}" $ algL ((p, (IndAngle, "")):ts) ms
algL ((p, (LexSpecial, "}")):ts) (0:ms) = insL p "}" $ algL ts ms
algL ((p, (LexSpecial, "}")):_) _ = [(p, (IndError, "unmatched }"))]
-- We zero the source column of explicit open braces.
-- TODO: It should be the other way around: implicit open braces should have
-- their source column zeroed, while explicit ones should have their true
-- column value. The check in `embrace` would have to be altered to match.
algL ((p, (LexSpecial, "{")):ts) ms = insL (setSourceColumn p 0) "{" $ algL ts (0:ms)
-- See Note 5. We handle this case at a higher level, in `embrace`.
-- algL (t:ts) (m:ms) | m /= 0 && bad = insL p "}" $ algL (t:ts) ms
algL (t:ts) ms = t : algL ts ms
algL [] [] = []
algL [] (m:ms) | m /= 0 = insL (newPos "" 0 0) "}" $ algL [] ms
               | otherwise = [(newPos "" 0 0, (IndError, "unmatched {"))]

insL :: SourcePos -> String -> [Lexeme] -> [Lexeme]
insL p s = ((p, (LexSpecial, s)):)

type Parser = Parsec [Lexeme] ()
data TopLevel = Super (String, Ast)
  | ClassDecl String String [(String, Type)]
  | InstanceDecl [(String, String)] String Type [(String, Ast)]
  | GenDecl (String, Type)
  | DataDecl [(String, (Maybe (Int, Int), Type))]
  | PublicDecl [String]
  | StoreDecl [String]
  deriving Show

arityFromType :: Type -> Int
arityFromType = f 0 where
  f acc (_ :-> r) = f (acc + 1) r
  f acc _ = acc

header :: Parser ([TopLevel], [Lexeme])
header = do
  ps <- option [] $ want "public" >>
    between (want "(") (want ")") (var `sepBy` want ",")
  ss <- option [] $ want "store" >>
    between (want "(") (want ")") (var `sepBy` want ",")
  (,) [PublicDecl ps, StoreDecl ss] <$> getInput

data Stmt = Stmt Ast | StmtArr String Ast | StmtLet [(String, Ast)]

toplevels :: Parser [TopLevel]
toplevels = topDecls where
  embrace p = do
    m <- sourceColumn <$> getPosition
    want "{"
    let
      next = ((:) <$> p <*> sepNext) <|> sepNext
      sepNext = (want ";" >> next) <|> (want "}" >> pure []) <|> autoClose
      noMatch = obtain IndError >>= fail
      autoClose = noMatch <|> do  -- Auto-insert "}".
        when (m == 0) $ fail "cannot implicitly close an explicit open brace"
        pure []
    next
  topDecls = embrace topDecl
  topDecl = (want "data" >> simpleType)
    <|> (want "class" >> classDecl)
    <|> (want "instance" >> instanceDecl)
    -- TODO: Left-factor genDecl and sc.
    <|> (GenDecl <$> genDecl) <|> sc
  classDecl = do
    s <- con
    t <- tyVar
    want "where"
    ms <- embrace cDecl
    pure $ ClassDecl s t ms
  instanceDecl = do
    ctx <- option [] $ try $ do
      ctxCls <- con
      ctxVar <- tyVar
      want "=>"
      pure [(ctxCls, ctxVar)]
    s <- con
    t <- inst
    want "where"
    ms <- embrace iDecl
    pure $ InstanceDecl ctx s t ms
  inst = (TC <$> con)
    <|> (TApp (TC "[]") . GV <$> between (want "[") (want "]") tyVar)
  cDecl = genDecl
  iDecl = do
    (fun:args) <- funlhs
    want "="
    ast <- expr
    pure (fun, if null args then ast else Ast $ Lam args ast)
  genDecl = try $ do
    v <- var
    want "::"
    t <- typeExpr
    pure (v, t)
  simpleType = do
    s <- con
    args <- many tyVar
    want "="
    let
      t = foldl' TApp (TC s) $ GV <$> args
      typeCon = do
        c <- con
        ts <- many atype
        pure (c, foldr (:->) t ts)
    typeCons <- typeCon `sepBy1` want "|"
    pure $ DataDecl [(c, (Just (i, arityFromType typ), typ))
      | (i, (c, typ)) <- zip [0..] typeCons]
  typeExpr = foldr1 (:->) <$> btype `sepBy1` want "->"
  btype = foldl1' TApp <$> many1 atype
  -- Unsupported: [] (->) (,{,}) constructors.
  atype = (TC <$> con)
    <|> (GV <$> tyVar)
    <|> (TApp (TC "[]") <$> between (want "[") (want "]") typeExpr)
    <|> (parenType <$> between (want "(") (want ")") (typeExpr `sepBy` want ","))
  parenType [x] = x
  parenType xs  = foldr1 TApp $ TC "()":xs
  sc = Super <$> letDefn
  funlhs = do
    v0 <- var
    scOp v0 <|> ((v0:) <$> many var)
  scOp l = do
    op <- varSym
    r <- var
    pure [op, l, r]
  expr = infixExp
  infixExp = bin 0 False
  bin 10 _ = lexp
  bin prec isR = rec False =<< bin (prec + 1) False where
    rec isL m = try (do
      o <- varSym <|> between (want "`") (want "`") var
      let (a, p) = fixity o
      when (p /= prec) $ fail ""
      case a of
        LAssoc -> do
          when isR $ fail "same precedence, mixed associativity"
          n <- bin (prec + 1) False
          rec True $ Ast $ Ast (Ast (Var o) :@ m) :@ n
        NAssoc -> do
          n <- bin (prec + 1) False
          pure $ Ast $ Ast (Ast (Var o) :@ m) :@ n
        RAssoc -> do
          when isL $ fail "same precedence, mixed associativity"
          n <- bin prec True
          pure $ Ast $ Ast (Ast (Var o) :@ m) :@ n
      ) <|> pure m
  letDefn = do
    (fun:args) <- funlhs
    want "="
    ast <- expr
    pure (fun, if null args then ast else Ast $ Lam args ast)
  doExpr = do
    want "do"
    ss <- embrace stmt
    case ss of
      [] -> fail "empty do block"
      _ -> desugarDo ss
  desugarDo [Stmt x] = pure x
  desugarDo [] = fail "do block must end with expression"
  desugarDo (h:rest) = do
    body <- desugarDo rest
    pure $ Ast $ case h of
      Stmt x -> Ast (Ast (Var ">>=") :@ x) :@ Ast (Lam ["_"] body)
      StmtArr v x -> Ast (Ast (Var ">>=") :@ x) :@ Ast (Lam [v] body)
      StmtLet ds -> Let ds body
  stmt = stmtLet <|> do
    v <- expr
    lArrStmt v <|> pure (Stmt v)
  lArrStmt v = want "<-" >> case v of
    Ast (Var s) -> StmtArr s <$> expr
    _ -> fail "want variable on left of (<-)"
  stmtLet = do
    want "let"
    ds <- embrace letDefn
    (want "in" >> Stmt . Ast . Let ds <$> expr) <|> pure (StmtLet ds)
  letExpr = do
    ds <- between (want "let") (want "in") $ embrace letDefn
    Ast . Let ds <$> expr
  caseExpr = do
    x <- between (want "case") (want "of") expr
    as <- embrace alt
    when (null as) $ fail "empty case"
    pure $ Ast $ Cas x as
  alt = do
    p <- expr
    want "->"
    x <- expr
    pure (p, x)
  -- TODO: Introduce patterns to deal with _.
  lambda = fmap Ast $ Lam <$> between (want "\\") (want "->") (many1 $ var <|> uscore) <*> expr
  lexp = lambda <|> caseExpr <|> letExpr <|> doExpr <|> foldl1' ((Ast .) . (:@)) <$> many1 atom
  uscore = want "_" >> pure "_"
  atom = qvar
    <|> (Ast . Var <$> uscore)
    <|> (Ast . Var <$> var)
    <|> (Ast . Var <$> con)
    <|> num <|> str <|> lis <|> enumLis <|> tup
  tup = do
    xs <- between (want "(") (want ")") $ expr `sepBy` want ","
    pure $ case xs of  -- Abuse Pack to represent tuples.
      [] -> Ast $ Pack 0 0
      [x] -> x
      _ -> foldl' ((Ast .) . (:@)) (Ast $ Pack 0 $ length xs) xs

  -- TODO: Left-factor lis and enumLis.
  lis = try $ do
    items <- between (want "[") (want "]") $ expr `sepBy` want ","
    pure $ foldr (\a b -> Ast (Ast (Ast (Var ":") :@ a) :@ b)) (Ast $ Var "[]") items
  enumLis = try $ between (want "[") (want "]") $ do
    a <- expr
    want ".."
    b <- expr
    pure $ Ast $ Ast (Ast (Var "enumFromTo") :@ a) :@ b

  splitDot s = second tail $ splitAt (fromJust $ elemIndex '.' s) s
  qvar = Ast . uncurry Qual . splitDot <$> obtain LexQual
  con = obtain LexCon
  num = Ast . I . read <$> obtain LexNumber
  str = Ast . S . sbs <$> obtain LexString
  tyVar = varId

var :: Parser String
var = varId <|> try (between (want "(") (want ")") varSym)

varId :: Parser String
varId = obtain LexVar

varSym :: Parser String
varSym = obtain LexVarSym

obtain :: LexemeType -> Parser String
obtain t = token show fst f where
  f (_, (t', s)) = bool Nothing (Just s) $ t == t'

want :: String -> Parser ()
want s = void $ token show fst f where
  f (_, (LexString, _)) = Nothing
  f (_, (_, t)) | s == t = Just ()
  f _ = Nothing

data Associativity = LAssoc | RAssoc | NAssoc deriving (Eq, Show)

standardFixities :: Map String (Associativity, Int)
standardFixities = M.fromList $ concatMap (f . words)
  [ "infixl 9 !!"
  , "infixr 9 ."
  , "infixr 8 ^ ^^ **"
  , "infixl 7 * / div mod rem quot"
  , "infixl 6 + -"
  , "infixr 5 : ++"
  , "infix 4 == /= < <= > >= elem notElem"
  , "infixr 3 &&"
  , "infixr 2 ||"
  , "infixl 1 >> >>="
  , "infixr 0 $ $! seq"
  ]
  where
    f (assoc:prec:ops) = flip (,) (parseAssoc assoc, read prec) <$> ops
    f _ = undefined
    parseAssoc "infix"  = NAssoc
    parseAssoc "infixl" = LAssoc
    parseAssoc "infixr" = RAssoc
    parseAssoc _ = error "BUG! bad associativity"

fixity :: String -> (Associativity, Int)
fixity o = fromMaybe (LAssoc, 9) $ M.lookup o standardFixities

parseDfnHs :: QQuoter -> String -> Either ParseError [TopLevel]
parseDfnHs qq s = do
  lexStream <- runParser (filler >> many rawTok) qq "" s
  (r0, rest) <- parse header "" lexStream
  fmap (r0 ++) $ parse toplevels "" $ (`algL` []) $ insertIndents rest

lexOffside :: String -> Either ParseError [String]
lexOffside s = map (snd . snd) . (`algL` []) . insertIndents
  <$> runParser (filler >> many rawTok) (\_ _ -> Left "no qq") "" s


================================================
FILE: src/Std.hs
================================================
module Std (stdBoost) where

import Boost
import DHC
import WasmOp

sp, hp, bp :: Int
[sp, hp, bp] = [0, 1, 2]

stdBoost :: Boost
stdBoost = Boost
  -- No Wasm Imports
  []
  -- Prelude definitions.
  (unlines
  [ "data Bool = False | True"
  , "data Maybe a = Nothing | Just a"
  , "data Either a b = Left a | Right b"
  , "fst p = case p of (x, y) -> x"
  , "snd p = case p of (x, y) -> y"
  , "f . g = \\x -> f (g x)"
  , "flip f = \\x y -> f y x"
  , "fromJust m = case m of {Just x -> x}"
  , "maybe n j m = case m of {Just x -> j x; Nothing -> n}"
  , "f >> g = f >>= \\_ -> g"
  , "bool f t b = case b of {False -> f; True ->t}"
  , "when b t = bool (pure ()) t b"
  , "f $ x = f x"
  , "id x = x"
  , "class Eq a where (==) :: a -> a -> Bool"
  , "class Monad m where"
  , "  (>>=) :: m a -> (a -> m b) -> m b"
  , "  pure :: a -> m a"
  -- Generates call_indirect ops.
  , "class Message a where callSlot :: I32 -> a -> IO ()"
  , "class Storage a where"
  , "  atoAnyRef :: a -> I32"
  , "  bfromAnyRef :: I32 -> a"
  , "  ctoUnboxed :: a -> Unboxed a"
  , "  dfromUnboxed :: Unboxed a -> a"
  , "set x y = fst x $ ctoUnboxed y"
  , "get x = snd x >>= pure . dfromUnboxed"
  , "instance Monad Maybe where"
  , "  x >>= f = case x of { Nothing -> Nothing; Just a -> f a }"
  , "  pure x = Just x"
  , "io_pure x rw = (x, rw)"
  , "io_bind f g rw = let {p = f rw} in case p of (a, rw1) -> g a rw1"
  , "instance Monad IO where"
  , "  (>>=) = io_bind"
  , "  pure = io_pure"
  , "instance Eq Int where (==) = eq_Int"
  , "instance Eq String where (==) = eq_String"
  , "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) } }"
  ])
  -- Haskell functions defined in wasm.
  [ ("+", (TC "Int" :-> TC "Int" :-> TC "Int", intAsm I64_add))
  , ("-", (TC "Int" :-> TC "Int" :-> TC "Int", intAsm I64_sub))
  , ("*", (TC "Int" :-> TC "Int" :-> TC "Int", intAsm I64_mul))
  , ("div", (TC "Int" :-> TC "Int" :-> TC "Int", intAsm I64_div_s))
  , ("mod", (TC "Int" :-> TC "Int" :-> TC "Int", intAsm I64_rem_s))
  , ("<", (TC "Int" :-> TC "Int" :-> TC "Bool", cmpAsm I64_lt_s))
  , (">", (TC "Int" :-> TC "Int" :-> TC "Bool", cmpAsm I64_gt_s))
  , ("<=", (TC "Int" :-> TC "Int" :-> TC "Bool", cmpAsm I64_le_s))
  , (">=", (TC "Int" :-> TC "Int" :-> TC "Bool", cmpAsm I64_ge_s))
  , ("&&", (TC "Bool" :-> TC "Bool" :-> TC "Bool", boolAsm I32_and))
  , ("||", (TC "Bool" :-> TC "Bool" :-> TC "Bool", boolAsm I32_or))
  , ("++", (TC "String" :-> TC "String" :-> TC "String", catAsm))
  , ("slice", (TC "Int" :-> TC "String" :-> TApp (TC "()") (TApp (TC "String") (TC "String")), sliceAsm))
  , ("undefined", (a, [Unreachable, End]))

  -- It'd be nice if these two were somehow only available internally to DHC.
  , ("eq_Int", (TC "Int" :-> TC "Int" :-> TC "Bool", cmpAsm I64_eq))
  , ("eq_String", (TC "String" :-> TC "String" :-> TC "Bool", strEqAsm))

  -- Programmers cannot call the following directly.
  -- We keep their types around for various checks.
  , ("#rundict", (TC "I32" :-> GV "a" :-> GV "b", runDictAsm))
  ]
  -- Internal wasm helpers.
  [ ("#memcpyhp", (([I32, I32], []), memcpyhpAsm))
  , ("#notmemcmp", (([I32, I32, I32], [I32]), notmemcmpAsm))
  ]
  where
    a = GV "a"

intAsm :: QuasiWasm -> [QuasiWasm]
intAsm op =
  [ Custom $ ReduceArgs 2
  , Get_global sp  -- PUSH [[sp + 4] + 8]
  , I32_load 2 4
  , I64_load 3 8
  , Get_global sp  -- sp = sp + 8
  , I32_const 8
  , I32_add
  , Set_global sp
  , Get_global sp  -- PUSH [[sp] + 8]
  , I32_load 2 0
  , I64_load 3 8
  , op
  , Custom $ CallSym "#pushint"
  , I32_const 12  -- UpdatePopEval 2
  , Custom $ CallSym "#updatepopeval"
  , End
  ]
cmpAsm :: QuasiWasm -> [QuasiWasm]
cmpAsm op =
  [ Custom $ ReduceArgs 2
  , Get_global hp  -- [hp] = TagSum
  , tag_const TagSum
  , I32_store 2 0
  -- [hp + 4] = [[sp + 4] + 8] == [[sp + 8] + 8]
  , Get_global hp  -- PUSH hp
  , Get_global sp  -- PUSH [[sp + 4] + 8]
  , I32_load 2 4
  , I64_load 3 8
  , Get_global sp  -- PUSH [[sp + 8] + 8]
  , I32_load 2 8
  , I64_load 3 8
  , op
  , I32_store 2 4
  , Get_global sp  -- [sp + 8] = hp
  , Get_global hp
  , I32_store 2 8
  , Get_global sp  -- sp = sp + 4
  , I32_const 4
  , I32_add
  , Set_global sp
  , Get_global hp  -- hp = hp + 8
  , I32_const 8
  , I32_add
  , Set_global hp
  , I32_const 12  -- UpdatePopEval 2
  , Custom $ CallSym "#updatepopeval"
  , End
  ]
boolAsm :: QuasiWasm -> [QuasiWasm]
boolAsm op =
  [ Custom $ ReduceArgs 2
  , Get_global hp  -- [hp] = TagSum
  , tag_const TagSum
  , I32_store 2 0
  -- [hp + 4] = [[sp + 4] + 4] `op` [[sp + 8] + 4]
  , Get_global hp
  , Get_global sp
  , I32_load 2 4
  , I32_load 2 4
  , Get_global sp
  , I32_load 2 8
  , I32_load 2 4
  , op
  , I32_store 2 4
  , Get_global sp  -- [sp + 8] = hp
  , Get_global hp
  , I32_store 2 8
  , Get_global sp  -- sp = sp + 4
  , I32_const 4
  , I32_add
  , Set_global sp
  , Get_global hp  -- hp = hp + 8
  , I32_const 8
  , I32_add
  , Set_global hp
  , I32_const 12  -- UpdatePopEval 2
  , Custom $ CallSym "#updatepopeval"
  , End
  ]
catAsm :: [QuasiWasm]
catAsm =
  [ Custom $ ReduceArgs 2
  , Get_global sp  -- PUSH sp
  , Get_global hp  -- PUSH hp
  , Get_global hp  -- [hp] = TagString
  , tag_const TagString
  , I32_store 2 0
  , Get_global hp -- [hp + 4] = hp + 16
  , Get_global hp
  , I32_const 16
  , I32_add
  , I32_store 2 4
  , Get_global hp -- [hp + 8] = 0
  , I32_const 0
  , I32_store 2 8
  , Get_global hp -- [hp + 12] = [[sp + 4] + 12] + [[sp + 8] + 12]
  , Get_global sp
  , I32_load 2 4
  , I32_load 2 12
  , Get_global sp
  , I32_load 2 8
  , I32_load 2 12
  , I32_add
  , I32_store 2 12
  , Get_global hp  -- hp = hp + 16
  , I32_const 16
  , I32_add
  , Set_global hp
  , Get_global sp  -- memcpyhp ([[sp + 4] + 4] + [[sp + 4] + 8]) [[sp + 4] + 12]
  , I32_load 2 4
  , I32_load 2 4
  , Get_global sp
  , I32_load 2 4
  , I32_load 2 8
  , I32_add
  , Get_global sp
  , I32_load 2 4
  , I32_load 2 12
  , Custom $ CallSym "#memcpyhp"
  , Get_global sp  -- memcpyhp ([[sp + 8] + 4] + [[sp + 8] + 8]) [[sp + 8] + 12]
  , I32_load 2 8
  , I32_load 2 4
  , Get_global sp
  , I32_load 2 8
  , I32_load 2 8
  , I32_add
  , Get_global sp
  , I32_load 2 8
  , I32_load 2 12
  , Custom $ CallSym "#memcpyhp"
  , I32_store 2 8  -- [sp + 8] = old_hp  ; Via POPs.
  , Get_global sp  -- sp = sp + 4
  , I32_const 4
  , I32_add
  , Set_global sp
  , I32_const 0  -- Align hp.
  , Get_global hp
  , I32_sub
  , I32_const 3
  , I32_and
  , Get_global hp
  , I32_add
  , Set_global hp
  , I32_const 12  -- UpdatePopEval 2
  , Custom $ CallSym "#updatepopeval"
  , End
  ]
memcpyhpAsm :: [QuasiWasm]
memcpyhpAsm =
  [ Loop Nada  -- while (local1 != 0) {
    [ Get_local 1
    , I32_eqz
    , Br_if 1
    , Get_local 1  -- local1 = local1 - 1
    , I32_const 1
    , I32_sub
    , Set_local 1
    , Get_global hp  -- [hp].8 = [local0].8
    , Get_local 0
    , I32_load8_u 0 0
    , I32_store8 0 0
    , Get_local 0  -- local0 = local0 + 1
    , I32_const 1
    , I32_add
    , Set_local 0
    , Get_global hp  -- hp = hp + 1
    , I32_const 1
    , I32_add
    , Set_global hp
    , Br 0
    ]
  , End
  ]
strEqAsm :: [QuasiWasm]
strEqAsm =
  [ Custom $ ReduceArgs 2
  , Get_global sp  -- PUSH sp
  , Get_global hp  -- PUSH hp
  , Get_global hp  -- [hp] = TagSum
  , tag_const TagSum
  , I32_store 2 0
  , Get_global hp  -- [hp + 4] = 0
  , I32_const 0
  , I32_store 2 4
  , Get_global sp  -- bp = [[sp + 4] + 12]
  , I32_load 2 4
  , I32_load 2 12
  , Set_global bp

  , Block Nada
    [ Get_global sp  -- if bp /= [[sp + 8] + 12] then break
    , I32_load 2 8
    , I32_load 2 12
    , Get_global bp
    , I32_ne
    , Br_if 0

    , Get_global hp  -- PUSH hp
    , Get_global sp  -- notmemcmp ([[sp + 4] + 4] + [[sp + 4] + 8]) ([[sp + 8] + 4] + [[sp + 8] + 8]) bp
    , I32_load 2 4
    , I32_load 2 4
    , Get_global sp
    , I32_load 2 4
    , I32_load 2 8
    , I32_add
    , Get_global sp
    , I32_load 2 8
    , I32_load 2 4
    , Get_global sp
    , I32_load 2 8
    , I32_load 2 8
    , I32_add
    , Get_global bp
    , Custom $ CallSym "#notmemcmp"
    , I32_store 2 4  -- [hp + 4] = result  ; Via POP.
    ]
  , I32_store 2 8  -- [sp + 8] = old_hp  ; Via POPs.
  , Get_global sp  -- sp = sp + 4
  , I32_const 4
  , I32_add
  , Set_global sp
  , Get_global hp  -- hp = hp + 8
  , I32_const 8
  , I32_add
  , Set_global hp
  , I32_const 12  -- UpdatePopEval 2
  , Custom $ CallSym "#updatepopeval"
  , End
  ]
notmemcmpAsm :: [QuasiWasm]
notmemcmpAsm =
  [ Loop Nada  -- while (local2 != 0) {
    [ Get_local 2
    , I32_eqz
    , If Nada [ I32_const 1 , Return ] []
    , Get_local 2  -- local2 = local2 - 1
    , I32_const 1
    , I32_sub
    , Set_local 2
    , Get_local 0  -- [local0].8 /= [local1].8 ?
    , I32_load8_u 0 0
    , Get_local 1
    , I32_load8_u 0 0
    , I32_ne
    , If Nada [ I32_const 0 , Return ] []
    , Get_local 0  -- local0 = local0 + 1
    , I32_const 1
    , I32_add
    , Set_local 0
    , Get_local 1  -- local1 = local1 + 1
    , I32_const 1
    , I32_add
    , Set_local 1
    , Br 0
    ]
  , Unreachable
  , End
  ]
sliceAsm :: [QuasiWasm]
sliceAsm =
  [ Custom $ ReduceArgs 2
  -- TODO: Handle lengths out of range.
  , Get_global sp  -- bp = [[sp + 4] + 8]
  , I32_load 2 4
  , I32_load 2 8
  , Set_global bp
  , Get_global hp  -- [hp] = TagSum | (2 << 8)
  , I32_const $ fromIntegral $ fromEnum TagSum + 256 * 2
  , I32_store 2 0
  , Get_global hp  -- [hp + 4] = 0
  , I32_const 0
  , I32_store 2 4
  , Get_global hp  -- [hp + 8] = hp + 16
  , Get_global hp
  , I32_const 16
  , I32_add
  , I32_store 2 8
  , Get_global hp  -- [hp + 12] = hp + 32
  , Get_global hp
  , I32_const 32
  , I32_add
  , I32_store 2 12
  , Get_global hp  -- [hp + 16] = TagString
  , tag_const TagString
  , I32_store 2 16
  , Get_global hp  -- [hp + 20] = [[sp + 8] + 4]
  , Get_global sp
  , I32_load 2 8
  , I32_load 2 4
  , I32_store 2 20
  , Get_global hp  -- [hp + 24] = [[sp + 8] + 8]
  , Get_global sp
  , I32_load 2 8
  , I32_load 2 8
  , I32_store 2 24
  , Get_global hp  -- [hp + 28] = bp
  , Get_global bp
  , I32_store 2 28
  , Get_global hp  -- [hp + 32] = TagString
  , tag_const TagString
  , I32_store 2 32
  , Get_global hp  -- [hp + 36] = [[sp + 8] + 4]
  , Get_global sp
  , I32_load 2 8
  , I32_load 2 4
  , I32_store 2 36
  , Get_global hp  -- [hp + 40] = [[sp + 8] + 8] + bp
  , Get_global sp
  , I32_load 2 8
  , I32_load 2 8
  , Get_global bp
  , I32_add
  , I32_store 2 40
  , Get_global hp  -- [hp + 44] = [[sp + 8] + 12] - bp
  , Get_global sp
  , I32_load 2 8
  , I32_load 2 12
  , Get_global bp
  , I32_sub
  , I32_store 2 44
  , Get_global sp  -- sp = sp + 4
  , I32_const 4
  , I32_add
  , Set_global sp
  , Get_global sp  -- [sp + 4] = hp
  , Get_global hp
  , I32_store 2 4
  , Get_global hp  -- hp = hp + 48
  , I32_const 48
  , I32_add
  , Set_global hp
  , I32_const 12  -- UpdatePopEval 2
  , Custom $ CallSym "#updatepopeval"
  , End
  ]

-- | Runs a method at a given index of a given dictionary.
-- Expects [I32, Coproduct] on top of the stack (both in normal form).
-- The coproduct represents a dictionary of methods for an instance of a
-- typeclass, e.g. the dictionary for the Monad instace of Maybe is:
--
--   Copro 0 [Maybe->>=, Maybe-pure]
runDictAsm :: [QuasiWasm]
runDictAsm =
  [ Get_global sp  -- [sp + 12] = [[sp + 8] + [[sp + 4] + 4]]
  , Get_global sp
  , I32_load 2 8
  , Get_global sp
  , I32_load 2 4
  , I32_load 2 4
  , I32_add
  , I32_load 2 0

  , I32_store 2 12
  , Get_global sp  -- sp = sp + 8
  , I32_const 8
  , I32_add
  , Set_global sp
  , Custom $ CallSym "#eval"
  , End
  ]


================================================
FILE: src/WasmOp.hs
================================================
{-# LANGUAGE CPP #-}
#ifdef __HASTE__
{-# LANGUAGE PackageImports #-}
#endif
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
module WasmOp
  ( WasmType(..), CustomWasmOp(..), WasmOp, zeroOperandOps, rZeroOps
  , followCalls, renumberCalls, WasmFun(..)
  ) where
#ifdef __HASTE__
import "mtl" Control.Monad.State
import qualified Data.Set as IS
import qualified Data.Map.Strict as IM
#else
import Control.Monad.State
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
#endif
import Data.Binary (Binary)
import Data.Int
import Data.Void
import GHC.Generics (Generic)

#ifdef __HASTE__
type IntMap = IM.Map Int
type IntSet = IS.Set Int
#endif

data WasmType = I32 | I64 | F32 | F64 | Func | AnyFunc | Nada
  | Ref String  -- Custom types used by Dfinity.
  deriving (Read, Show, Eq, Ord, Generic)
instance Binary WasmType

data WasmFun = WasmFun
  { typeSig :: ([WasmType], [WasmType])
  , localVars :: [WasmType]
  , funBody :: [WasmOp]
  } deriving Show

-- Much of this file was generated from:
--   http://webassembly.org/docs/binary-encoding/

data CustomWasmOp a = Custom a
  | 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
  | 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
  | Unreachable | Nop | Else | End | Return
  | Block WasmType [CustomWasmOp a] | Loop WasmType [CustomWasmOp a] | If WasmType [CustomWasmOp a] [CustomWasmOp a]
  | Get_local Int | Set_local Int | Tee_local Int | Get_global Int | Set_global Int
  | I32_const Int32 | I64_const Int64 | F32_const Float | F64_const Double
  | Br_table [Int] Int
  | Br Int | Br_if Int
  | Call Int
  | Call_indirect ([WasmType], [WasmType])
  | Drop | Select
  deriving (Show, Eq, Functor)

type WasmOp = CustomWasmOp Void

zeroOperandOps :: [(Int, WasmOp)]
zeroOperandOps = cmpOps ++ ariOps ++ crops ++ others ++ parametrics where
  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)]
  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)]
  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)]
  others = [(0x00, Unreachable), (0x01, Nop), (0x0b, End), (0x0f, Return)]
  parametrics = [(0x1a, Drop), (0x1b, Select)]

rZeroOps :: [(WasmOp, Int)]
rZeroOps = (\(a, b) -> (b, a)) <$> zeroOperandOps

followCalls :: [Int] -> IntMap [WasmOp] -> IntSet
followCalls ns m = execState (go ns) $ IS.fromList ns where
  go :: [Int] -> State IntSet ()
  go (n:rest) = do
    maybe (pure ()) tr $ IM.lookup n m
    go rest
  go [] = pure ()
  tr (w:rest) = do
    case w of
      Call i -> do
        s <- get
        when (IS.notMember i s) $ do
          put $ IS.insert i s
          go [i]
      Loop _ b -> tr b
      Block _ b -> tr b
      If _ t f -> do
        tr t
        tr f
      _ -> pure ()
    tr rest
  tr [] = pure ()

renumberCalls :: IntMap Int -> [WasmOp] -> [WasmOp]
renumberCalls m ws = case ws of
  [] -> []
  (w:rest) -> ren w:rec rest
  where
  rec = renumberCalls m
  ren w = case w of
    Call i -> Call $ m IM.! i
    Loop t b -> Loop t $ rec b
    Block t b -> Block t $ rec b
    If t a b -> If t (rec a) (rec b)
    x -> x


================================================
FILE: test/Main.hs
================================================
{-# LANGUAGE QuasiQuotes #-}
import Control.Arrow
import Control.Monad
import Data.Bits
import qualified Data.ByteString as B
import Data.ByteString.Char8 (unpack)
import Data.ByteString.Short (ShortByteString, fromShort, toShort)
import Data.Char (chr)
import Data.Int
import Data.List (foldl')
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import Data.Word
import Test.HUnit
import Text.Heredoc (here, there)
import Asm
import Boost
import DHC
import Hero.Hero
import Parse
import SoloSyscall
import Std
import Demo

data Node = NInt Int64 | NString ShortByteString | NAp Int Int | NGlobal Int String | NInd Int | NCon Int [Int] | RealWorld [String] deriving Show

-- | Interprets G-Machine instructions.
gmachine :: String -> String
gmachine prog = if "main_" `M.member` funs then
    go (Right <$> [PushGlobal "main_", Eval]) [] M.empty
  else
    go (Right <$> [PushGlobal "main", MkAp, Eval]) [0] $ M.singleton 0 $ RealWorld []
  where
  drop' n as | n > length as = error "BUG!"
             | otherwise     = drop n as
  (funs, m) = either error id $ hsToGMachine toyBoost prog
  toyBoost = Boost [] []
    -- We'll intercept `putStr` so there's no need for an implementation.
    [ ("putStr", (TC "String" :-> TApp (TC "IO") (TC "()"), []))
    , ("putInt", (TC "Int" :-> TApp (TC "IO") (TC "()"), []))
    ] []
  arity "putStr" = 1
  arity "putInt" = 1
  arity s | Just a <- M.lookup s funs = a
  arity s = arityFromType $ fst $ fromJust $ lookup s $ boostPrims stdBoost
  go (fOrIns:rest) s h = either prim exec fOrIns where
    k = M.size h
    heapAdd x = M.insert k x h
    intInt f = go rest (k:srest) $ heapAdd $ NInt $ f x y where
      (s0:s1:srest) = s
      NInt x = h M.! s0
      NInt y = h M.! s1
    intCmp f = go rest (k:srest) $ heapAdd $ NCon (fromEnum $ f x y) [] where
      (s0:s1:srest) = s
      NInt x = h M.! s0
      NInt y = h M.! s1
    boolOp f = go rest (k:srest) $ heapAdd $ NCon (f x y) [] where
      (s0:s1:srest) = s
      NCon x [] = h M.! s0
      NCon y [] = h M.! s1
    rwAdd msg heap | RealWorld ms <- heap M.! 0 =
      M.insert 0 (RealWorld $ ms ++ [msg]) heap
    rwAdd _ _ = error "BUG! Expect RealWorld at 0 on heap"
    prims = M.fromList
      [ ("+", intInt (+))
      , ("-", intInt (-))
      , ("*", intInt (*))
      , ("div", intInt div)
      , ("mod", intInt mod)
      , ("eq_Int", intCmp (==))
      , ("<", intCmp (<))
      , (">", intCmp (>))
      , ("&&", boolOp min)
      , ("||", boolOp max)
      , ("++", let
        (s0:s1:srest) = s
        NString str0 = h M.! s0
        NString str1 = h M.! s1
        t = toShort $ fromShort str0 <> fromShort str1
        in go rest (k:srest) $ heapAdd $ NString t)
      , ("putStr", let
        k1 = k + 1
        (s0:srest) = s
        NString str = h M.! s0
        in go rest (k:srest) $ rwAdd (unpack $ fromShort str) $ M.insert k1 (NCon 0 []) $ heapAdd $ NCon 0 [k1, 0])
      , ("#rundict", let
        (s0:s1:srest) = s
        NInt n = h M.! s0
        NCon _ as = h M.! s1
        in go rest (as!!(fromIntegral (n - 8) `div` 4):srest) h)
      ]
    prim g | Just f <- M.lookup g prims = f
           | otherwise = error $ "unsupported: " ++ g
    exec ins = case ins of
      Trap -> "UNREACHABLE"
      PushInt n -> go rest (k:s) $ heapAdd $ NInt n
      PushRef n -> go rest (k:s) $ heapAdd $ NInt $ fromIntegral n
      PushString str -> go rest (k:s) $ heapAdd $ NString str
      Push n -> go rest (s!!n:s) h
      PushGlobal v -> go rest (k:s) $ heapAdd $ NGlobal (arity v) v
      MkAp -> let (s0:s1:srest) = s in go rest (k:srest) $ heapAdd $ NAp s0 s1
      UpdateInd n -> go rest (tail s) $ M.insert (s!!(n + 1)) (NInd $ head s) h
      UpdatePopEval n -> go (Right Eval:rest) (drop' (n + 1) s) $ M.insert (s!!(n + 1)) (NInd $ head s) h
      Alloc n -> go rest ([k..k+n-1]++s) $ M.union h $ M.fromList $ zip [k..k+n-1] (repeat $ NInd 0)
      Slide n -> let (s0:srest) = s in go rest (s0:drop' n srest) h
      Copro n l -> go rest (k:drop' l s) $ heapAdd $ NCon n $ take l s
      Split _ -> let
        (s0:srest) = s
        NCon _ as = h M.! s0
        in go rest (as ++ srest) h
      Eval -> case h M.! head s of
        NInd i -> go (Right Eval:rest) (i:tail s) h
        NAp a _ -> go (Right Eval:rest) (a:s) h
        NGlobal n g -> let
          p | g == "putStr" = [Right $ Push 0, Right Eval, Left "putStr", Right $ Slide 3]
            | Just is <- M.lookup g m = Right <$> is
            | M.member g prims = (Right <$> concat (replicate n [Push $ n - 1, Eval]))
              ++ [Left g, Right $ UpdatePopEval n]
            | otherwise = error $ "unsupported: " ++ g
          debone i = r where NAp _ r = h M.! i
          in go (p ++ rest) ((debone <$> take n (tail s)) ++ drop' n s) h
        _ -> go rest s h
      Casejump alts -> let
        x = case h M.! head s of
          NCon n _ -> fromIntegral n
          _ -> undefined
        body = case lookup (Just x) alts of
          Just b -> b
          _ -> fromJust $ lookup Nothing alts
        in go ((Right <$> body) ++ rest) s h
      _ -> error "unsupported"
  go [] [r] h
    | "main_" `M.member` funs = case h M.! r of
      NInt n -> show n
      NCon n _ -> "Pack " ++ show n
      NString s -> show s
      _ -> error "expect NInt or NCon on stack"
    | NCon 0 [_, o] <- h M.! r, RealWorld out <- h M.! o = show out
  go [] s h = error $ "bad stack: " ++ show (s, h)

gmachineTests :: [Test]
gmachineTests = (\(result, source) -> TestCase $
  assertEqual source result $ gmachine source) <$>
    -- Test cases from Peyton Jones and Lester,
    -- "Implementing Functional Languages; a tutorial".
    -- Each case either contains a `main` function of type `IO a`, or
    -- a pure `main_` function which we reduce to WHNF.
    [ ("81", "square x = x * x; main_ = square (square 3)")
    , ("3", "i x = x; main_ = i 3")
    , ("3", "id = s k k; s x y z = x z (y z); k x y = x; main_ = id 3")
    , ("3", "id = s k k; s x y z = x z (y z); k x y = x; twice f x = f (f x);"
      ++ "main_ = twice twice twice id 3")
    , ("3", "i x = x; twice f x = f (f x ); main_ = twice (i i i) 3")
    , ("4", concat
      [ "cons a b cc cn = cc a b; nil cc cn = cn; hd list = list k abort;"
      , "abort = abort;"
      , "k x y = x; k1 x y = y;"
      , "tl list = list k1 abort;"
      -- The following fail to type-check:
      --   infinite x = cons x (infinite x);
      -- so we make do with a fixed list.
      , "main_ = hd (tl (cons 3 (cons 4 nil)))"
      ])
    , ("17", "main_ = 4*5+(2-5)")
    , ("8", "twice f x = f (f x); inc x = x + 1; main_ = twice twice inc 4")
      -- Change list representation so that `length` can be typed.
    , ("3", concat
      [ "length xs = xs (\\h a -> 1 + a) 0;"
      , "cons h t c n = c h(t c n); nil c n = n;"
      , "main_ = length (cons 3 (cons 3 (cons 3 nil)))"
      ])
    , ("120", "fac n = case n == 0 of { True -> 1; False -> (n * fac (n - 1)) }\nmain_ = fac 5")
    , ("2", "gcd a b = case a == b of { True -> a; False -> case a < b of"
      ++ " { True -> gcd b a; False -> gcd b (a - b) } }; main_ = gcd 6 10")
    , ("9", "nfib n = case n < 2 of { True -> 1; False -> 1 + nfib (n - 1) + nfib (n - 2) }; main_ = nfib 4")
    , ("Pack 1", "main_ = 2 + 2 == 4")
    , ("Pack 0", "main_ = 2 + 2 == 5")
    , ("Pack 1", "main_ = [1,1,2] == [1,1,2]")
    , ("Pack 1", "main_ = [[1,1],[2]] == [[1,1],[2]]")
    , ("Pack 0", "main_ = [[1],[2]]   == [[1,1],[2]]")
    , ("Pack 0", "main_ = (==) [[1,1],[2]] [[1,3],[2]]")
    , ("Pack 1", "f x = x == x; main_ = f [1,2,3]")
    , ("1", "main_ = (case 3 > 2 of True -> 1; False -> 0)")
    , ("\"Hello, World\"", "main_ = \"Hello\" ++ \", \" ++ \"World\"")
    , (show ["hello"], "main = putStr \"hello\"")
    , (show ["hello", "world"], "main = putStr \"hello\" >>= \\x -> putStr \"world\"")
    , (show ["hello", "hello"], "putHello = putStr \"hello\" ; main = putHello >>= \\_ -> putHello")
    , (show ["hello", "world"], unlines
      [ "main = do"
      , "  putStr \"hello\""
      , "  putStr \"world\""
      ])
    , (show ["one", "two", "three"], unlines
      [ "main = do"
      , "  putStr \"one\""
      , "  putStr \"two\""
      , "  putStr \"three\""
      ])
    , (show ["hello", "world"], unlines
      [ "main = do"
      , "  x <- pure \"world\""
      , "  putStr \"hello\""
      , "  putStr x"
      ])
    ]

lexOffsideTests :: [Test]
lexOffsideTests = (\(result, source) -> TestCase $
  assertEqual source (Right result) $ lexOffside source) <$>
    [ (["{", "main", "=", "foo", "}"], "main = foo")
    , (["{", "x", "=", "1", ";", "y", "=", "2", "}"], "x = 1\ny = 2")
    , (["{", "main", "=", "do", "{", "foo", ";", "bar", "}", "}"], unlines
      [ "main = do"
      , "  foo"
      , "  bar"
      ])
    -- The following lexes "incorrectly" (the parentheses and curly braces
    -- are improperly nested), but is fixed in the parser. See Note 5 of
    -- https://www.haskell.org/onlinereport/haskell2010/haskellch10.html
    , (words "{ f x = ( case x of { True -> 1 ; False -> 0 ) } }",
      "f x = (case x of True -> 1; False -> 0)")
    ]

demoCases :: [(String, String)]
demoCases = second ("public (main)\n" ++) <$>
  [ ("Hello, World!\n", "main = putStr \"Hello, World!\\n\"")
  , ("Hello, Quasi!\n", "main = putStr [here|Hello, Quasi!\n|]")
  , ("9876543210", "main = putInt 9876543210")
  , ("42", unlines
    [ "main = putInt (f 42)"
    , "f :: Int -> Int"
    , "f x = x"
    ])
  , ("123", unlines
    [ "main = maybe undefined putInt $ do"
    , "  x <- (Just 5 >>= (\\x -> Just $ x * 24))"
    , "  pure (x + 3)"
    ])
  , ("314", unlines
    [ "data List x = Nil | Cons x (List x)"
    , "main = f (Cons 3 (Cons 1 (Cons 4 Nil)))"
    , "f l = case l of"
    , "  Nil -> putStr \"\""
    , "  Cons n rest -> do"
    , "    putInt n"
    , "    f rest"
    ])
  , ("1123459", unlines
    [ "data Tree a = Nil | Node a (Tree a) (Tree a)"
    , "main = pr (f Nil [3, 1, 4, 1, 5, 9, 2])"
    , "f t l = case l of"
    , "  [] -> t"
    , "  x:xs -> f (ins x t) xs"
    , "ins x t = case t of"
    , "  Nil -> Node x Nil Nil"
    , "  Node y a b -> case x > y of"
    , "    True -> Node y a (ins x b)"
    , "    False -> Node y (ins x a) b"
    , "pr t = case t of"
    , "  Nil -> pure ()"
    , "  Node x a b -> do"
    , "    pr a"
    , "    putInt x"
    , "    pr b"
    ])
  , ("hello", [here|
f $ x = f x
xs =  [(271828, "l"), (318310, "he"), (618034, "o")]
main = do
  putStr $ fromJust $ lookup 318310 xs
  putStr $ fromJust $ lookup 271828 xs
  putStr $ fromJust $ lookup 271828 xs
  putStr $ fromJust $ lookup 618034 xs
lookup n xs = case xs of
  [] -> Nothing
  ((k, v):rest) -> case k == n of
    True -> Just v
    False -> lookup n rest
|])
  , (unlines
    [ "recursion with fix: 10000"
    , "5! + (10 + 20 + 30 + 40 + 50) = 270"
    ], [there|test/example.hs|])
  ]

demoTests :: [Test]
demoTests = (\(result, source) -> TestCase $ runDemo source >>= assertEqual source result) <$> demoCases

-- Could be turned into a runhaskell-like tool with:
--
--   main = putStr =<< runDemo =<< getContents
runDemo :: String -> IO String
runDemo src = case hsToWasm demoBoost src of
  Left err -> error err
  Right ints -> let
    vm = decode $ either error id $ parseWasm $ B.pack $ fromIntegral <$> ints
    in fst . snd <$> invoke (sys, undefined) [] (getExport "main" vm) [] ("", vm)
  where
  sys ("system", "putStr") [I32_const ptr, I32_const len] (s, vm) =
    pure ([], (s ++ [chr $ getNum 1 (ptr + i) vm | i <- [0..len - 1]], vm))
  sys ("system", "putInt") [I64_const i] (s, vm) = pure ([], (s ++ show i, vm))
  sys _ _ _ = error "BUG! bad syscall"

altWebTests :: [Test]
altWebTests = (\(result, source) -> TestCase $ runAltWeb source >>= assertEqual source result) <$> demoCases

-- Alternate host for putStr and putInt using SoloSyscall.
altWebBoost :: Boost
altWebBoost = Boost [(("dhc", "system"), ([I32, I32, I32], []))]
  []
  (second (uncurry genSyscallFromType) <$>
  [ ("putStr", (21, TC "String" :-> io (TC "()")))
  , ("putInt", (22, TC "Int" :-> io (TC "()")))
  ])
  []
  where io = TApp (TC "IO")

runAltWeb :: String -> IO String
runAltWeb src = case hsToWasm altWebBoost src of
  Left err -> error err
  Right ints -> let
    vm = decode $ either error id $ parseWasm $ B.pack $ fromIntegral <$> ints
    in fst . snd <$> invoke (altWebSys, undefined) [] (getExport "main" vm) [] ("", vm)

altWebSys :: (String, String) -> [WasmOp] -> (String, Hero) -> IO ([WasmOp], (String, Hero))
altWebSys ("dhc", "system") [I32_const n, I32_const sp, I32_const hp] (s, vm)
  | n == 21 = do
    when (getTag /= 6) $ error "BUG! want String"
    let
      ptr = getNum 4 (addr + 4) vm
      off = getNum 4 (addr + 8) vm
      slen = getNum 4 (addr + 12) vm
    pure ([], (s ++ [chr $ getNum 1 (ptr + off + i) vm | i <- [0..slen - 1]]
      , putNum 4 hp (5 :: Int)
      $ putNum 4 (hp + 4) (0 :: Int)
      $ putNum 4 sp hp
      $ putNum 4 (sp - 4) (hp + 8)
      vm))
  | n == 22 = do
    when (getTag /= 3) $ error "BUG! want Int"
    pure ([], (s ++ show (getNum 8 (addr + 8) vm :: Int)
      , putNum 4 hp (5 :: Int)
      $ putNum 4 (hp + 4) (0 :: Int)
      $ putNum 4 sp hp
      $ putNum 4 (sp - 4) (hp + 8)
      vm))
  | otherwise = error $ "BUG! bad syscall " ++ show n
  where
    addr = getNum 4 (sp + 4) vm :: Int32
    getTag = getNum 1 addr vm :: Int
altWebSys _ _ _ = error "BUG! bad syscall "

main :: IO Counts
main = runTestTT $ TestList $ lexOffsideTests ++ gmachineTests ++ demoTests ++ altWebTests

getNum :: (Integral n) => Int -> Int32 -> Hero -> n
getNum w addr vm = sum $ zipWith (*) bs ((256^) <$> [(0 :: Int)..]) where
  bs = fromIntegral . (`getMemory` vm) . (addr +) <$> [0..fromIntegral w-1]

putNum :: (Integral n) => Int -> Int32 -> n -> Hero -> Hero
putNum w addr n vm = foldl' f vm [0..w-1] where
  f m k = putMemory (addr + fromIntegral k) (getByte k) m
  getByte k = fromIntegral $ ((fromIntegral n :: Word64) `shiftR` (8*k)) .&. 255


================================================
FILE: test/SoloSyscall.hs
================================================
-- A simple syscall scheme.
--
-- We expect a single import function:
--   dhc.system : I32 -> I32 -> I32 -> ()
-- which expects the syscall number, heap pointer, and stack pointer.

module SoloSyscall (genSyscall, genSyscallFromType) where

import Data.Int
import Boost
import DHC
import WasmOp

sp, hp :: Int
[sp, hp] = [0, 1]

genSyscallFromType :: Int64 -> Type -> (Type, [QuasiWasm])
genSyscallFromType n t = (t, genSyscall (isIO t) n $ fromIntegral $ arityFromType t)

isIO :: Type -> Bool
isIO (_ :-> u) = isIO u
isIO (TC "IO" `TApp` _) = True
isIO _ = False

-- | Generates the WebAssembly for `dhc.system n sp hp` where `n` is the
-- syscall number and `m` is the number of arguments the syscall expects.
-- We evaluate `m` arguments on the heap to WHNF.
-- For pure syscalls we return the result.
-- For impure syscalls we return the tuple (result, #RealWorld).
-- TODO: Get rid of #RealWorld token.
genSyscall :: Bool -> Int64 -> Int64 -> [QuasiWasm]
genSyscall impure svc argCount =
  [ Custom $ ReduceArgs $ fromIntegral argCount
  , I32_const $ fromIntegral svc
  , Get_global sp
  , Get_global hp
  , Custom $ CallSym "dhc.system"
  -- Our convention:
  --   [sp] = result ; [sp - 4] = hp_new
  -- Return (result, #RealWorld).
  ] ++ if impure then
      [ Get_global sp  -- hp = [sp - 4]
      , I32_const 4
      , I32_sub
      , I32_load 2 0
      , Set_global hp
      , Get_global hp  -- [hp] = TagSum | (2 << 8)
      , I32_const $ fromIntegral $ fromEnum TagSum + 256 * 2
      , I32_store 2 0
      , Get_global hp  -- [hp + 4] = 0
      , I32_const 0
      , I32_store 2 4
      , Get_global hp  -- [hp + 8] = [sp]
      , Get_global sp
      , I32_load 2 0
      , I32_store 2 8
      , Get_global hp  -- [hp + 12] = 42
      , I32_const 42
      , I32_store 2 12
      , Get_global sp  -- [sp + 8*argCount + 8] = hp
      , Get_global hp
      , I32_store 2 $ 8*fromIntegral argCount + 8
      , Get_global hp  -- hp = hp + 16
      , I32_const 16
      , I32_add
      , Set_global hp
      , Get_global sp  -- sp = sp + 8*argCount + 4
      , I32_const $ 8*fromIntegral argCount + 4
      , I32_add
      , Set_global sp
      , End
      ]
    else
      [ Get_global sp  -- hp = [sp - 4]
      , I32_const 4
      , I32_sub
      , I32_load 2 0
      , Set_global hp
      -- TODO: Make it lazy with an indirection.
      , Get_global sp  -- [sp + 8*argCount + 4] = [sp]
      , Get_global sp
      , I32_load 2 0
      , I32_store 2 $ 8*fromIntegral argCount + 4
      , Get_global sp  -- sp = sp + 8*argCount
      , I32_const $ 8*fromIntegral argCount
      , I32_add
      , Set_global sp
      , End
      ]


================================================
FILE: test/example.hs
================================================
-- To get this working in GHC, uncomment the following 2 lines:
--   import Prelude hiding (foldr, uncurry, sum, map, enumFromTo)
--   putInt = print

-- Gratuitous mutual recursion.
factorial n = case n == 0 of True  -> 1
                             False -> n * factorial2 (n - 1)
factorial2 n = case n == 0 of True  -> 1
                              False -> n * factorial (n - 1)
foldr f n xs = case xs of [] -> n
                          (a:as) -> f a (foldr f n as)
uncurry f p = case p of (a, b) -> f a b
sum = foldr (+) 0
enumFromTo a b = case a > b of True  -> []
                               False -> a : enumFromTo (a + 1) b
map f = foldr ((:) . f) []
tenTimes x = 10 * x
f rec n = case n == 0 of True -> 0
                         False -> rec (n - 1) + 2*n - 1
main = do
  putStr "recursion with fix: "
  let fix f = f $ fix f
  putInt $ fix f 100
  putStr "\n5! + (10 + 20 + 30 + 40 + 50) = "
  putInt $ uncurry (+) (factorial 5, sum $ map tenTimes [1..5])
  putStr "\n"


================================================
FILE: test/rundhc.hs
================================================
import Data.Char
import qualified Data.ByteString as B
import Hero.Hero

main :: IO ()
main = putStr =<< runDemo =<< B.getContents

runDemo :: B.ByteString -> IO String
runDemo asm = stateVM . snd <$> runWasm "main" [] (mkHeroVM "" syscall wasm [])
  where
  wasm = either error id $ parseWasm asm
  syscall ("system", "putStr") vm [I32_const ptr, I32_const len] = pure ([],
    putStateVM (stateVM vm ++ [chr $ getNumVM 1 (ptr + i) vm | i <- [0..len - 1]]) vm)
  syscall ("system", "putInt") vm [I32_const lo, I32_const hi] = pure ([],
    putStateVM (stateVM vm ++ show (fromIntegral lo + fromIntegral hi * 2^(32 :: Integer) :: Integer)) vm)
  syscall a _ b = error $ show ("BUG! bad syscall", a, b)