hbf (empty) → 0.1.0.0
raw patch · 22 files changed
+2917/−0 lines, 22 filesdep +HUnitdep +basedep +binarysetup-changed
Dependencies added: HUnit, base, binary, bytestring, criterion, deepseq, doctest, filepath, hbf, hedgehog, hedgehog-checkers, optparse-applicative, parsec, primitive, smallcheck, tasty, tasty-discover, tasty-hedgehog, tasty-hunit, tasty-smallcheck, temporary, text, transformers, vector
Files
- ChangeLog.md +7/−0
- LICENSE +674/−0
- README.md +74/−0
- Setup.hs +3/−0
- bench/Main.hs +48/−0
- hbf.cabal +200/−0
- src/HBF/Compiler.hs +557/−0
- src/HBF/Eval.hs +235/−0
- src/HBF/Parser.hs +91/−0
- src/HBF/Types.hs +193/−0
- src/exe/hbf/Main.hs +12/−0
- src/exe/hbfc/Main.hs +20/−0
- tests/CompilerTest.hs +204/−0
- tests/EvalTest.hs +89/−0
- tests/Helper.hs +139/−0
- tests/IntegrationTests.hs +35/−0
- tests/ParserTest.hs +42/−0
- tests/allfeatures.bf +86/−0
- tests/doctest.hs +4/−0
- tests/factor.bf +195/−0
- tests/squares.bf +8/−0
- tests/test.hs +1/−0
+ ChangeLog.md view
@@ -0,0 +1,7 @@+# Revision history for hbf++## 0.1.0.0 -- 2018-06-23++* First version.+** Compiler working.+** VM working.
+ LICENSE view
@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ 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.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ 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 <http://www.gnu.org/licenses/>.++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:++ <program> Copyright (C) <year> <name of author>+ 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+<http://www.gnu.org/licenses/>.++ 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+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ README.md view
@@ -0,0 +1,74 @@+# HBF [](https://travis-ci.org/paraseba/hbf)++An unoptimized Brainfuck optimizing compiler and evaluator.++[HBF](https://github.com/paraseba/hbf) can compile standard Brainfuck code into an optimized+Intermediate Representation (IR). This IR can later be executed for faster Brainfuck program+evaluation.+++## Getting Started++### Installing+Use your preferred method for installing HBF from [Hackage](fixme-link). If you prefer to build from source+you can use cabal.++### Usage++Let's say you have a Brainfuck program in the file `mandelbrot.bf`, for example,+you can get one [here](https://github.com/pablojorge/brainfuck/blob/master/programs/mandelbrot.bf)++You can compile the program to the Intermediate Representation using the `hbfc` executable provided by this project:++```+hbfc mandelbrot.bf+```++That will create a file `mandelbrot.bfc` in the same directory. If you want the output in a different+path you cane use `--output` option to `hbfc`++Now, you can run the compiled program:++```+hbf mandelbrot.bfc+```++and get something like:+++++There are several options to both the compiler and the evaluator, to modify levels of optimization, output and others. Try+`--help` to learn more.+++## Hacking+HBF has heavily documented code. Take a look at the documentation on [Hackage](fixme-link).+++### Running the tests++```+cabal test+```++Test coverage report for the last build can be found [here](https://paraseba.gitlab.io/hbf/coverage/hpc_index.html).++### Running the benchmarks++```+cabal bench+```++Benchmark report for the last build can be found [here](https://paraseba.gitlab.io/hbf/bench.html).++## License++This project is licensed under the GPL-3 License - see the [LICENSE](LICENSE) file for details++Copyright 2018 Sebastian Galkin.++## Acknowledgments++This work is based on the excellent project [bfoptimization](https://github.com/matslina/bfoptimization) by matslina: +
+ Setup.hs view
@@ -0,0 +1,3 @@+import Distribution.Simple++main = defaultMain
+ bench/Main.hs view
@@ -0,0 +1,48 @@+module Main where++import Control.Monad.Trans.State (execStateT)+import Criterion.Main+import qualified Data.Text.Lazy.IO as TIO+import System.FilePath (takeBaseName)++import HBF.Compiler as C+import qualified HBF.Eval as E+import HBF.Types++type BenchmarkName = String++type ProgramInput = MockIO++type UnoptimizedP = Program Optimized++type OptimizedP = Program Optimized++programEnv ::+ FilePath+ -> String+ -> IO (BenchmarkName, ProgramInput, OptimizedP, UnoptimizedP)+programEnv file input = do+ code <- TIO.readFile file+ let (Right (optimized, _)) = C.inMemoryCompile C.defaultCompilerOptions code+ let (Right (unoptimized, _)) =+ inMemoryCompile noOptimizationCompilerOptions code+ return (takeBaseName file, mkMockIOS input, optimized, unoptimized)++mkProgramGroup ::+ (BenchmarkName, ProgramInput, OptimizedP, UnoptimizedP) -> Benchmark+mkProgramGroup ~(name, input, optimized, unoptimized) =+ bgroup+ name+ [ bench "fully optimized" $ whnfIO $ execStateT (E.eval optimized) input+ , bench "not optimized" $ whnfIO $ execStateT (E.eval unoptimized) input+ ]++main :: IO ()+main =+ defaultMain+ [ bgroup+ "programs"+ [ env (programEnv "tests/factor.bf" "254504\n") mkProgramGroup+ , env (programEnv "tests/allfeatures.bf" "0") mkProgramGroup+ ]+ ]
+ hbf.cabal view
@@ -0,0 +1,200 @@+-- This file has been generated from package.yml by hpack version 0.27.0.+--+-- see: https://github.com/sol/hpack+--+-- hash: 52d387cac5e4409ba9bbc2b21b18ab93084d896c2ca023d84c601d76dc628a8f++name: hbf+version: 0.1.0.0+cabal-version: >= 1.10+build-type: Simple+license: GPL-3+license-file: LICENSE+tested-with: GHC == 8.2.1, GHC == 8.2.2, GHC == 8.4.1, GHC == 8.4.2, GHC == 8.4.3+author: Sebastian Galkin+maintainer: paraseba@gmail.com+copyright: Sebastian Galkin, 2018+synopsis: An optimizing Brainfuck compiler and evaluator+description: hbf is a compiler and executor of Brainfuck programs. It provides two executables: @hbfc@ the Brainfuck compiler, and @hbf@ the virtual machine that executes compiled Brainfuck programs.+homepage: https://gitlab.com/paraseba/hbf+bug-reports: https://gitlab.com/paraseba/hbf/issues+category: Language++extra-source-files:+ ChangeLog.md+ README.md+ tests/allfeatures.bf+ tests/factor.bf+ tests/squares.bf++source-repository head+ type: git+ location: git@gitlab.com:paraseba/hbf.git++flag dump+ description: Dump stg and core files+ manual: True+ default: False++flag profile+ description: Enable profiling in benchmarks+ manual: True+ default: False++library+ exposed-modules:+ HBF.Types+ HBF.Parser+ HBF.Eval+ HBF.Compiler+ other-modules:+ Paths_hbf+ build-depends:+ base >=4.10.0.0 && <4.13+ , binary >=0.8.5.1+ , bytestring >=0.10.8.0+ , deepseq >=1.4.3.0+ , filepath >=1.4.1.2+ , optparse-applicative >=0.14.0.0+ , parsec >=3.1.13.0+ , primitive >=0.6.2.0+ , text >=1.2.2.0+ , transformers >=0.5.2.0+ , vector >=0.12.0.1+ if flag(dump)+ ghc-options: -ddump-simpl -ddump-stg -ddump-to-file -dsuppress-idinfo -dsuppress-coercions -dsuppress-type-applications -dsuppress-uniques+ if flag(profile)+ ghc-options: -fprof-auto+ hs-source-dirs:+ src+ default-language: Haskell2010+ ghc-options: -Wall -fwarn-incomplete-record-updates -fwarn-monomorphism-restriction++executable hbf+ main-is: Main.hs+ other-modules:+ Paths_hbf+ hs-source-dirs:+ src/exe/hbf+ ghc-options: -Wall -fwarn-incomplete-record-updates -fwarn-monomorphism-restriction+ build-depends:+ base >=4.10.0.0 && <4.13+ , binary >=0.8.5.1+ , bytestring >=0.10.8.0+ , deepseq >=1.4.3.0+ , filepath >=1.4.1.2+ , hbf+ , optparse-applicative >=0.14.0.0+ , parsec >=3.1.13.0+ , primitive >=0.6.2.0+ , text >=1.2.2.0+ , transformers >=0.5.2.0+ , vector >=0.12.0.1+ if flag(profile)+ ghc-options: -fprof-auto -with-rtsopts='-p -s -h -i0.05'+ default-language: Haskell2010++executable hbfc+ main-is: Main.hs+ other-modules:+ Paths_hbf+ hs-source-dirs:+ src/exe/hbfc+ ghc-options: -Wall -fwarn-incomplete-record-updates -fwarn-monomorphism-restriction+ build-depends:+ base >=4.10.0.0 && <4.13+ , binary >=0.8.5.1+ , bytestring >=0.10.8.0+ , deepseq >=1.4.3.0+ , filepath >=1.4.1.2+ , hbf+ , optparse-applicative >=0.14.0.0+ , parsec >=3.1.13.0+ , primitive >=0.6.2.0+ , text >=1.2.2.0+ , transformers >=0.5.2.0+ , vector >=0.12.0.1+ default-language: Haskell2010++test-suite doctest+ type: exitcode-stdio-1.0+ main-is: doctest.hs+ hs-source-dirs:+ tests+ ghc-options: -Wall -fwarn-incomplete-record-updates -fwarn-monomorphism-restriction -threaded -with-rtsopts=-N+ build-depends:+ base >=4.10.0.0 && <4.13+ , binary >=0.8.5.1+ , bytestring >=0.10.8.0+ , deepseq >=1.4.3.0+ , doctest+ , filepath >=1.4.1.2+ , hbf+ , optparse-applicative >=0.14.0.0+ , parsec >=3.1.13.0+ , primitive >=0.6.2.0+ , text >=1.2.2.0+ , transformers >=0.5.2.0+ , vector >=0.12.0.1+ default-language: Haskell2010++test-suite test+ default-language: Haskell2010+ type: exitcode-stdio-1.0+ hs-source-dirs:+ tests+ main-is: test.hs+ build-depends:+ HUnit >=1.3.1.0+ , base >=4.10.0.0 && <4.13+ , binary >=0.8.5.1+ , bytestring >=0.10.8.0+ , deepseq >=1.4.3.0+ , filepath >=1.4.1.2+ , hbf+ , hedgehog >=0.5+ , hedgehog-checkers >=0.1.0.0+ , optparse-applicative >=0.14.0.0+ , parsec >=3.1.13.0+ , primitive >=0.6.2.0+ , smallcheck >=1.1+ , tasty >=0.11.2.1+ , tasty-discover >=2.0.0+ , tasty-hedgehog >=0.1.0.0+ , tasty-hunit >=0.9.2+ , tasty-smallcheck >=0.8+ , temporary >=1.2.0.3+ , text >=1.2.2.0+ , transformers >=0.5.2.0+ , vector >=0.12.0.1+ ghc-options: -Wall -fwarn-incomplete-record-updates -fwarn-monomorphism-restriction -threaded -with-rtsopts=-N+ other-modules:+ ParserTest+ CompilerTest+ EvalTest+ IntegrationTests+ Helper++benchmark evalbench+ other-modules:+ Paths_hbf+ hs-source-dirs:+ bench+ ghc-options: -Wall -fwarn-incomplete-record-updates -fwarn-monomorphism-restriction -threaded -with-rtsopts=-N+ type: exitcode-stdio-1.0+ main-is: Main.hs+ default-language: Haskell2010+ build-depends:+ base >=4.10.0.0 && <4.13+ , binary >=0.8.5.1+ , bytestring >=0.10.8.0+ , criterion >=1.1.4.0+ , deepseq >=1.4.3.0+ , filepath >=1.4.1.2+ , hbf+ , optparse-applicative >=0.14.0.0+ , parsec >=3.1.13.0+ , primitive >=0.6.2.0+ , text >=1.2.2.0+ , transformers >=0.5.2.0+ , vector >=0.12.0.1
+ src/HBF/Compiler.hs view
@@ -0,0 +1,557 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE RecordWildCards #-}++{-|+Description : Brainfuck compilation to IR+Copyright : (c) Sebastian Galkin, 2018+License : GPL-3++In this module we:++ - Convert 'Text' into a Brainfuck intermediate representation (IR) consisting of lists of 'Op's.+ - Provide optimization rules to speed up IR execution.+ - Parse compiler command line options+-}+module HBF.Compiler+ ( module HBF.Compiler+ -- * Reexport from "BFP.Parser"+ , BFP.ParseError+ ) where++import Control.Monad (when)+import Control.Monad.Trans.State (State, execState, get, modify, put)+import qualified Data.Binary as B+import Data.ByteString.Lazy (ByteString)+import Data.Coerce (coerce)+import Data.Foldable (traverse_)+import Data.Functor.Identity (Identity)+import Data.Maybe (fromMaybe)+import Data.Semigroup (Semigroup (..), (<>))+import Data.Text.Lazy (Text)+import qualified Data.Text.Lazy.IO as TIO+import Data.Tuple (swap)+import Options.Applicative (Parser, ParserInfo, ParserResult,+ argument, defaultPrefs,+ execParserPure, fullDesc,+ handleParseResult, header, help,+ helper, info, long, metavar, option,+ optional, progDesc, short, str,+ switch, (<**>))+import System.Environment (getArgs)+import System.FilePath ((-<.>))+import qualified Text.Parsec as Parsec+import Text.Parsec.Pos (initialPos)++import qualified HBF.Parser as BFP+import HBF.Types++-- * Compilation+-- | Encode the compiled file into the given path.+saveCompilerOutput :: Program Optimized -> FilePath -> IO ()+saveCompilerOutput = flip B.encodeFile . instructions++-- | Use the given 'CompilerOptions' to parse, compile and optimize the text representation of a+-- Brainfuck program into the IR. 'cOptsSource' and 'cOptsOut' in the compiler options are ignored.+inMemoryCompile ::+ CompilerOptions+ -> Text+ -> Either BFP.ParseError (Program Optimized, CompilationSummary)+inMemoryCompile opts code =+ (\p -> (p, summarizeCompilation p)) . optimize opts <$> BFP.parseProgram code++-- | Compilation summary for the user. It contains overview information and+-- statistics about the compilation result.+newtype CompilationSummary = CompilationSummary+ { compNumInstructions :: Int+ } deriving (Show)++-- | Summarize a compiled program creating the 'CompilationSummary'+summarizeCompilation :: Program Optimized -> CompilationSummary+summarizeCompilation = CompilationSummary . length . instructions++-- | Use 'CompilerOptions' to read, compile, optimize, and save a program from/to the filesystem.+-- Input and output files are provided by 'cOptsSource' and 'cOptsOut'.+compile :: CompilerOptions -> IO (Either BFP.ParseError CompilationSummary)+compile opts@CompilerOptions {..} = do+ when cOptsVerbose $ do+ putStrLn "Compiler options:"+ print opts+ compileResult <- inMemoryCompile opts <$> TIO.readFile cOptsSource+ either+ (return . Left)+ (\p -> save p >> (return . Right . snd) p)+ compileResult+ where+ outPath = fromMaybe (cOptsSource -<.> "bfc") cOptsOut+ save (program, _) = saveCompilerOutput program outPath++-- | Apply optimizations to the 'Unoptimized' program turning. The optimizations that+-- will be available are the ones specified by the 'CompilerOptions' given.+optimize :: CompilerOptions -> Program Unoptimized -> Program Optimized+optimize CompilerOptions {..} p = foldl (flip ($)) base optimizations+ where+ base = toIR p+ opt condition f =+ if condition+ then f+ else id+ optimizations =+ [ opt cOptsClearLoopOptimization clearOpt+ , opt cOptsMulOptimization mulOpt+ , opt cOptsScanOptimization scanOpt+ , opt cOptsOffsetInstructionsOptimization offsetInstructionOpt+ , opt cOptsFusionOptimization fusionOpt+ ]++-- | Given a parsed program, turn it into an optimized one, but with the null optimization.+-- Effectively this is only a type change.+toIR :: Program Unoptimized -> Program Optimized+toIR = coerce++-- * Optimization+-- | Helper type to apply the Fuse optimization using a 'Monoid'.+newtype FusedProgram = Fused+ { unfused :: Program Optimized+ } deriving (Show)++-- | This 'Semigroup' for 'FusedProgram' does all the fusion optimization work.+-- When two contiguous optimizations can be fused into one, '<>' will reduce the+-- size of the list in the 'FusedProgram'.+--+-- Examples of fusable operations:+--+-- - (Inc a offset) (Inc b offset) -> (Inc (a+b) offset)+-- - (Move 3 offset) (Move (-3) offset) -> NoOp+-- - (Clear offset) (Clear offset) -> Clear offset+-- - (Scan Up offset) (Scan _ offset') -> Scan Up offset+instance Semigroup FusedProgram where+ Fused (Program p1) <> Fused (Program p2) = Fused $ Program $ fuse p1 p2+ where+ fuse :: [Op] -> [Op] -> [Op]+ fuse [] ops = ops+ fuse ops [] = ops+ fuse [op1] (op2:more) = join op1 op2 ++ more+ fuse (op1:more) ops2 = op1 : fuse more ops2+ join :: Op -> Op -> [Op]+ join (Inc a n) (Inc b m)+ | n == m = ifNotZero (flip Inc n) $ a + b+ join (Move a) (Move b) = ifNotZero Move $ a + b+ join (In a n) (In b m)+ | n == m = ifNotZero (flip In n) $ a + b+ join (Out a n) (Out b m)+ | n == m = ifNotZero (flip Out n) $ a + b+ join (Clear n) (Clear m)+ | n == m = [Clear n]+ -- once a scan is found, another one won't move the pointer+ join (Scan Up o1) (Scan _ o2)+ | o1 == o2 = [Scan Up o1]+ join (Scan Down o1) (Scan _ o2)+ | o1 == o2 = [Scan Down o1]+ join a b = [a, b]+ ifNotZero f n = [f n | n /= 0]++-- | Use the 'Semigroup' instance and an empty program as 'mempty'.+instance Monoid FusedProgram where+ mempty = Fused mempty+ mappend = (<>)++-- | Apply the fusion optimization using the 'FusedProgram' 'Monoid' instance.+--+-- The fusion optimization consist of turning multiple instructions into one. For example+-- if the original Brainfuck code contains '++++', this would be parsed as+--+-- @+--'Program' ['Inc' 1 0, 'Inc' 1 0, 'Inc' 1 0, 'Inc' 1 0]+-- @+--+-- but it would be fused to a single IR instruction: @Inc 4 0@.+--+-- >>> fusionOpt $ Program [Inc 1 0, Inc 1 0, Inc 1 0, Inc 1 0]+-- [Inc 4 0]+--+-- Similarly, other instructions,+-- like 'Move', 'In', 'Out', 'Clear' and 'Scan' can be fused as long as the offset at which they+-- must be applied is the same.+--+-- Non fusable operation remain unchanged:+--+-- >>> fusionOpt $ Program [Inc 1 0, Inc 1 1]+-- [Inc 1 0,Inc 1 1]+fusionOpt :: Program Optimized -> Program Optimized+fusionOpt = unfused . foldMap (Fused . Program . optimizeIn) . instructions+ where+ optimizeIn (Loop as) = [Loop inner | not (null inner)]+ where+ inner = instructions $ fusionOpt $ Program as+ optimizeIn other = [other]++-- | Helper function used to implement optimizations+-- Iterate over all 'Program' instructions searching for 'Loop's. For each 'Loop'+-- apply 'f'. If 'f' returns a list of new operations, replace the original loop with+-- the new instructions. If 'f' returns 'Nothing', process recursively the loop instructions.+liftLoop :: ([Op] -> Maybe [Op]) -> Program o -> Program o+liftLoop f = Program . (>>= g) . instructions+ where+ g :: Op -> [Op]+ g (Loop ops) =+ fromMaybe ((: []) . Loop . instructions . liftLoop f $ Program ops) $+ f ops+ g other = [other]++-- | Basic optimization that turns the loop @[-]@ into a single instruction 'Clear'.+-- Useful because clearing a memory position is a pretty common operation in Brainfuck and+-- very expensive if treated as a loop.+--+-- >>> :set -XOverloadedStrings+-- >>> Right (res, _) = inMemoryCompile defaultCompilerOptions "[-]"+-- >>> res+-- [Clear 0]+clearOpt :: Program Optimized -> Program Optimized+clearOpt = liftLoop onLoops+ where+ onLoops :: [Op] -> Maybe [Op]+ onLoops [Inc (-1) 0] = Just [Clear 0]+ onLoops _ = Nothing++-- | Copy and multiply optimization. A very common usage of loops is to copy the value of a memory+-- position to a different: @[->>+<<]@ this will move the contents of the current memory position+-- to places to the right, also clearing the original position to zero. If we change the number of @+@+-- operations we get multiplication, if we have several groups of @++..@ operations we get multiple copies.+-- In the general case, for example:+--+-- >>> :set -XOverloadedStrings+-- >>> Right (res, _) = inMemoryCompile defaultCompilerOptions "[->+>++>++++<<<]"+-- >>> res+-- [Mul 1 0 1,Mul 2 0 2,Mul 4 0 3,Clear 0]+--+-- The original Brainfuck copies the current position one place to the right, doubles+-- the current position two places to the right, and quadruples the current position three places to the right;+-- finally zeroing the current position. With the mul optimization in this function, all that loop would be+-- replaced by 4 instructions.+mulOpt :: Program Optimized -> Program Optimized+mulOpt = liftLoop onLoops+ where+ onLoops :: [Op] -> Maybe [Op]+ onLoops ops = makeOp <$> eitherToMaybe (Parsec.parse mulP "" ops)+ where+ makeOp :: [(MulFactor, MemOffset)] -> [Op]+ makeOp = (++ [Clear 0]) . snd . foldl it (0, [])+ where+ it (totalOff, res) (fact, off) =+ (totalOff + off, res ++ [Mul fact 0 (off + totalOff)]) -- todo very inefficient foldr++-- | Implement the scan optimization. Another common operation in Brainfuck is to search for the first zero+-- in the neighboring memory, either to the right or to the left @[>]@ or @[<]@. These loops can be replaced+-- for a more optimal search, represented as a single @'Scan' 'Up'@ or @'Scan' 'Down'@ instruction.+--+-- >>> scanOpt $ Program [Loop [Move 1]]+-- [Scan Up 0]+scanOpt :: Program Optimized -> Program Optimized+scanOpt = liftLoop onLoops+ where+ onLoops :: [Op] -> Maybe [Op]+ onLoops [Move 1] = Just [Scan Up 0]+ onLoops [Move (-1)] = Just [Scan Down 0]+ onLoops _ = Nothing++-- | Helper datastructure to implement a stateful transformation in 'offsetInstructionOpt'.+data OffsetState = OffSt+ { stOptimized :: [Op] -- ^ The optimized program so far+ , stBatch :: [Op] -- ^ The current batch of instructions being optimized (between loops)+ , stOffset :: MemOffset -- ^ The current offset since the last loop+ } deriving (Show)++-- | Start state for 'offsetInstructionOpt'.+emptyState :: OffsetState+emptyState = OffSt [] [] 0++-- | Implement the offset instruction optimization. This is probably the most complex+-- optimization implemented in the library.+--+-- In streams of instructions between loops, there is no need to keep updating the current position+-- if we can keep track of where the different operations should be applied. This is a trade-off+-- of time (not updating the pointer) by space (keeping track of the offset in every operation).+-- For example the following unoptimized code+--+--+-- >>> offsetInstructionOpt $ Program [Loop [], Move 1, Inc 1 0, Move 2, Clear 0, Mul 2 0 1, Loop []]+-- [Loop [],Inc 1 1,Clear 3,Mul 2 3 1,Move 3,Loop []]+--+-- And the optimization eliminated one 'Move' instruction. In general, for larger programs the gain+-- will be more noticeable.+--+-- An important detail to take into account is that 'Scan' operations break the stream of operations+-- that can be optimized together, and turn the accumulated offset back to zero:+--+-- >>> offsetInstructionOpt $ Program [Loop [], Move 1, Inc 1 0, Scan Up 0, Inc 0 2, Loop []]+-- [Loop [],Inc 1 1,Scan Up 1,Inc 0 2,Loop []]+offsetInstructionOpt :: Program Optimized -> Program Optimized+offsetInstructionOpt -- We implement this as a stateful computation for code clarity+ =+ Program .+ stOptimized .+ (`execState` emptyState) .+ (*> finishLastBatch) . traverse_ processOp . instructions+ where+ processOp :: Op -> State OffsetState ()+ processOp (Loop l) = do+ let newLoop = Loop (instructions $ offsetInstructionOpt (Program l))+ finishBatch+ modify $ \s@OffSt {..} -> s {stOptimized = newLoop : stOptimized}+ processOp (Move n) = get >>= \s -> put s {stOffset = stOffset s + n}+ processOp (Inc n off) = add off (Inc n)+ processOp (In n off) = add off (In n)+ processOp (Out n off) = add off (Out n)+ processOp (Clear off) = add off Clear+ processOp (Mul factor from to) = add from (\o -> Mul factor o to)+ processOp (Scan d off) = do+ OffSt {..} <- get+ put+ OffSt+ { stOffset = 0+ , stOptimized = stOptimized+ , stBatch = Scan d (off + stOffset) : stBatch+ }+ add :: MemOffset -> (MemOffset -> Op) -> State OffsetState ()+ add off op =+ get >>= \s@OffSt {..} -> put s {stBatch = op (off + stOffset) : stBatch}+ finishBatch :: State OffsetState ()+ finishBatch = do+ s@OffSt {..} <- get+ let batch =+ if stOffset /= 0+ then Move stOffset : stBatch+ else stBatch+ put s {stBatch = [], stOffset = 0, stOptimized = batch ++ stOptimized}+ finishLastBatch :: State OffsetState ()+ finishLastBatch = do+ finishBatch+ modify $ \s@OffSt {..} -> s {stOptimized = reverse stOptimized}++-- * Loading Compiled Code+-- | Load a compiled program from 'saveCompilerOutput' output.+load :: ByteString -> Program Optimized+load = B.decode++-- | Load a compiled program saved with 'saveCompilerOutput'.+loadFile :: FilePath -> IO (Program Optimized)+loadFile = B.decodeFile++-- * Compiler Flags+-- | Command line flags to the Brainfuck compiler+data CompilerOptions = CompilerOptions+ { cOptsOut :: Maybe FilePath -- ^ Where to put the compiled output, if 'Nothing' use the input basename with bfc extension+ , cOptsFusionOptimization :: Bool -- ^ Enable fusion optimization+ , cOptsClearLoopOptimization :: Bool -- ^ Enable clear loop optimization+ , cOptsMulOptimization :: Bool -- ^ Enable mul loop optimization+ , cOptsScanOptimization :: Bool -- ^ Enable scan loop optimization+ , cOptsOffsetInstructionsOptimization :: Bool -- ^ Enable offset instructions optimization+ , cOptsVerbose :: Bool -- ^ Output more debugging information+ , cOptsSource :: FilePath -- ^ Input source to the compiler, this should be Brainfuck code+ } deriving (Show)++optionsP :: Parser CompilerOptions+optionsP =+ (\output disableAll fusion clear mul scan offset verbose source ->+ CompilerOptions+ { cOptsOut = output+ , cOptsFusionOptimization = not disableAll || fusion+ , cOptsClearLoopOptimization = not disableAll || clear+ , cOptsMulOptimization = not disableAll || mul+ , cOptsScanOptimization = not disableAll || scan+ , cOptsOffsetInstructionsOptimization = not disableAll || offset+ , cOptsVerbose = verbose+ , cOptsSource = source+ }) <$>+ optional+ (option+ str+ (long "output" <> short 'o' <> metavar "OUT" <>+ help "Compiled output path")) <*>+ switch+ (long "disable-all-optimizations" <> short 'd' <>+ help "Disable all optimizations") <*>+ switch+ (long "fusion" <>+ help+ "Reenable fusion optimization (turn multiple + or > into a single operation)") <*>+ switch+ (long "clear" <>+ help "Reenable clear loop optimization (turn [-] into a single operation)") <*>+ switch+ (long "mul" <>+ help+ "Reenable mul loop optimization (turn [->++>+++<<] into [Mul(1, 2) Mul(2,3)] Clear operations)") <*>+ switch+ (long "scan" <>+ help "Reenable scan loop optimization (turn [>] into ScanR operation)") <*>+ switch+ (long "offset" <>+ help+ "Reenable offset instructions optimization (turn >>+>->> into Inc 1 2, Inc (-1) 1, Move 1, Move 1, Move 1, Move 1, Move 1, operation)") <*>+ switch+ (long "verbose" <> short 'v' <> help "Output more debugging information") <*>+ argument str (metavar "SRC" <> help "Input source code file")++options :: ParserInfo CompilerOptions+options =+ info+ (optionsP <**> helper)+ (fullDesc <> progDesc "Compile Brainfuck code in SRC file" <>+ header "An optimizing Brainfuck compiler and evaluator")++-- | Default compiler options: all optimizations, not verbose, no input or output files.+defaultCompilerOptions :: CompilerOptions+defaultCompilerOptions =+ CompilerOptions+ { cOptsOut = Nothing+ , cOptsFusionOptimization = True+ , cOptsClearLoopOptimization = True+ , cOptsMulOptimization = True+ , cOptsScanOptimization = True+ , cOptsOffsetInstructionsOptimization = True+ , cOptsVerbose = False+ , cOptsSource = ""+ }++-- | Compiler options: all optimizations off.+noOptimizationCompilerOptions :: CompilerOptions+noOptimizationCompilerOptions =+ CompilerOptions+ { cOptsOut = Nothing+ , cOptsFusionOptimization = False+ , cOptsClearLoopOptimization = False+ , cOptsMulOptimization = False+ , cOptsScanOptimization = False+ , cOptsOffsetInstructionsOptimization = False+ , cOptsVerbose = False+ , cOptsSource = ""+ }++-- | Parse a list of command line arguments+parsePure :: [String] -> ParserResult CompilerOptions+parsePure = execParserPure defaultPrefs options++-- | Parse a list of command line arguments printing errors to the stderr+unsafeParse :: [String] -> IO CompilerOptions+unsafeParse = handleParseResult . parsePure++-- | Parse command line arguments printing errors to the stderr+parse :: IO CompilerOptions+parse = getArgs >>= unsafeParse++----------------------- implementation details ----------------------+-- * Implementation Detail: Parsing Lists of Instructions+-- | This parser is used to implement the mul optimization. See 'mulOpt'.+type ProgramParser a = Parsec.ParsecT [Op] () Identity a++-- | Parse successfully if the token satisfies the predicate.+satisfy' :: Show t => (t -> Bool) -> Parsec.ParsecT [t] () Identity t+satisfy' predicate = Parsec.token showTok posFromTok testTok+ where+ showTok t = show t+ posFromTok _ = initialPos ""+ testTok t =+ if predicate t+ then Just t+ else Nothing++-- | Parse movement to the right (\>), returning the offset value.+--+-- >>> Parsec.parse mrightP "" [Move 3]+-- Right 3+--+-- >>> Data.Either.isLeft $ Parsec.parse mrightP "" [Move (-1)]+-- True+mrightP :: ProgramParser MemOffset+mrightP =+ satisfy' isRight <&> \case+ Move n -> n+ _ -> undefined++-- | Parsemovement to the left (\<), returning the offset value.+--+-- >>> Parsec.parse mleftP "" [Move (-3)]+-- Right 3+--+-- >>> Data.Either.isLeft $ Parsec.parse mleftP "" [Move 1]+-- True+mleftP :: ProgramParser MemOffset+mleftP =+ satisfy' isLeft <&> \case+ Move n -> (negate n)+ _ -> undefined++-- | Parse increment, returning total increment.+--+-- >>> Parsec.parse plusP "" [Inc 3 0]+-- Right 3+--+-- >>> Data.Either.isLeft $ Parsec.parse plusP "" [Inc (-2) 0]+-- True+plusP :: ProgramParser Int+plusP =+ satisfy' isPlus <&> \case+ Inc n 0 -> n+ _ -> undefined++-- | Parse decrement, returning total decrement.+--+-- >>> Parsec.parse minusP "" [Inc (-3) 0]+-- Right 3+--+-- >>> Data.Either.isLeft $ Parsec.parse minusP "" [Inc 2 0]+-- True+minusP :: ProgramParser Int+minusP =+ satisfy' isMinus <&> \case+ Inc n 0 -> (negate n)+ _ -> undefined++-- | Sum the result of a parser applied repeatedly+--+-- >>> Parsec.parse (summedP plusP) "" [Inc 3 0, Inc 1 0, Inc (-4) 0]+-- Right 4+summedP :: Num n => ProgramParser n -> ProgramParser n+summedP = fmap sum . Parsec.many1++-- | Full multiple copy/multiply operation parser. Returns the set of factors and relative, incremental offsets.+--+-- >>> Parsec.parse mulP "" [Inc (-1) 0, Move 1, Inc 2 0, Move 3, Inc 1 0, Move (-4)]+-- Right [(2,1),(1,3)]+mulP :: ProgramParser [(MulFactor, MemOffset)]+mulP = do+ _ <- minusP+ copies <- Parsec.many1 shiftFactorP+ let totalShift = sum $ map fst copies+ back <- summedP mleftP+ Parsec.eof+ if back == coerce totalShift+ then return (fmap swap copies)+ else Parsec.unexpected "number of left returns to close the loop"+ where+ shiftFactorP = (,) <$> summedP mrightP <*> fmap MulFactor (summedP plusP)++-- | Is the instruction a right movement?+isRight :: Op -> Bool+isRight (Move n)+ | n > 0 = True+isRight _ = False++-- | Is the instruction a left movement?+isLeft :: Op -> Bool+isLeft (Move n)+ | n < 0 = True+isLeft _ = False++-- | Is the instruction an increment?+isPlus :: Op -> Bool+isPlus (Inc n 0)+ | n > 0 = True+isPlus _ = False++-- | Is the instruction a decrement?+isMinus :: Op -> Bool+isMinus (Inc n 0)+ | n < 0 = True+isMinus _ = False
+ src/HBF/Eval.hs view
@@ -0,0 +1,235 @@+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# OPTIONS_GHC -fno-full-laziness #-}++{-|+Description : Brainfuck Virtual Machine+Copyright : (c) Sebastian Galkin, 2018+License : GPL-3++Functions to evaluate a compiled Brainfuck program.+-}+module HBF.Eval+ ( MachineType+ , eval+ , evalWith+ , evalWithIO+ , evalWithMachine+ , emptyMachine+ , mkMachine+ , VMOptions(..)+ , defaultVMOptions+ , unsafeParse+ , parse+ , parsePure+ ) where++import Control.Monad (replicateM_, when)+import Control.Monad.Primitive (PrimMonad, PrimState)+import Data.Coerce (coerce)+import Data.Int (Int8)+import Data.Maybe (fromMaybe)+import Data.Monoid ((<>))+import qualified Data.Vector.Fusion.Stream.Monadic as VStream+import qualified Data.Vector.Generic as GV+import qualified Data.Vector.Generic.Mutable as MV+import qualified Data.Vector.Unboxed+import Options.Applicative (Parser, ParserInfo,+ ParserResult, argument,+ auto, defaultPrefs,+ execParserPure, fullDesc,+ handleParseResult, header,+ help, helper, info, long,+ metavar, option, progDesc,+ short, str, switch, value,+ (<**>))+import System.Environment (getArgs)++import HBF.Types++-- | An alias for a 'Machine' in which memory is an unboxed vector of bytes.+type MachineType = Machine (Data.Vector.Unboxed.Vector Int8)++{-# INLINABLE eval #-}+-- | Evaluate the given program returning the end state of the 'Machine'. The evaluation can+-- happen in any 'PrimMonad' for which we can do I/O. The reason to use 'PrimState' is that+-- we will use mutable vectors for the evaluation.+eval :: (PrimMonad m, MachineIO m) => Program Optimized -> m MachineType+eval = evalWithMachine defaultVMOptions emptyMachine++{-# INLINABLE evalWith #-}+-- | Evaluate the given program returning the end state of the 'Machine'. The evaluation can+-- happen in any 'PrimMonad' for which we can do I/O. The reason to use 'PrimState' is that+-- we will use mutable vectors for the evaluation. 'VMOptions' are used to tune the details+-- of the VM, like available memory, verbosity, etc.+evalWith ::+ (PrimMonad m, MachineIO m)+ => VMOptions+ -> Program Optimized+ -> m MachineType+evalWith opts program =+ evalWithMachine opts (mkMachine (vmOptsMemoryBytes opts)) program++{-# INLINABLE evalWithIO #-}+-- | Evaluate the given program returning the end state of the 'Machine'. The evaluation+-- happens in IO, so Input/Output is done to the console.+evalWithIO :: VMOptions -> Program Optimized -> IO MachineType+evalWithIO opts program = do+ machine <- evalWith opts program+ when (vmOptsDumpMemory opts) $ print machine+ return machine++{-# SPECIALISE evalWithMachine ::+ VMOptions -> MachineType -> Program Optimized -> IO MachineType #-}++{-# INLINABLE evalWithMachine #-}+-- | Evaluate the given program returning the end state of the 'Machine'. The evaluation can+-- happen in any 'PrimMonad' for which we can do I/O. The reason to use 'PrimState' is that+-- we will use mutable vectors for the evaluation. 'VMOptions' are used to tune the details+-- of the VM, like memory available, verbosity, etc. The evaluation starts with the specified+-- 'MachineType', so the memory and initial pointer can be configured before running.+evalWithMachine ::+ forall m. (PrimMonad m, MachineIO m)+ => VMOptions+ -> MachineType+ -> Program Optimized+ -> m MachineType+evalWithMachine _ Machine {..} program = do+ mem <- GV.thaw memory+ finalPointer <- mutableEval (instructions program) mem 0+ finalMemory <- GV.unsafeFreeze mem+ return Machine {memory = finalMemory, pointer = finalPointer}+ -- For some reason making this function a top level binding brings down performance by compiling+ -- without native arithmetic. Even if we add SPECIALIZE pragma+ -- Maybe this is the reason why we also need -fno-full-laziness+ where+ mutableEval ::+ forall v. (MV.MVector v Int8)+ => [Op]+ -> v (PrimState m) Int8+ -> MemOffset+ -> m MemOffset+ mutableEval [] _ pos = return pos+ mutableEval (op:ops) mem pos =+ case op of+ Inc n memOffset ->+ MV.unsafeModify mem (+ fromIntegral n) (o2i $ pos + memOffset) *>+ mutableEval ops mem pos+ Move n -> mutableEval ops mem (pos + coerce n)+ Out times memOffset -> do+ val <- MV.unsafeRead mem (o2i $ pos + memOffset)+ replicateM_ times (putByte val)+ mutableEval ops mem pos+ In times memOffset ->+ if times == 0+ then mutableEval ops mem pos+ else let input :: m (Maybe Int8)+ input =+ foldr (flip (*>)) (return Nothing) $+ replicate times getByte+ in do input >>=+ MV.write mem (o2i $ pos + memOffset) . fromMaybe 0+ mutableEval ops mem pos+ Loop l -> do+ let go pos' = do+ condition <- MV.unsafeRead mem (o2i pos')+ if condition == 0+ then mutableEval ops mem pos'+ else (do pos'' <- mutableEval l mem pos'+ go pos'')+ go pos+ Clear offset ->+ MV.unsafeWrite mem (o2i $ pos + offset) 0 *> mutableEval ops mem pos+ Mul factor from to -> do+ x <- MV.unsafeRead mem (o2i $ pos + from)+ MV.unsafeModify+ mem+ (\old -> old + x * factor2i factor)+ (o2i $ pos + from + to)+ mutableEval ops mem pos+ Scan Up offset ->+ let start = o2i $ pos + offset+ slice :: v (PrimState m) Int8+ slice = MV.slice start (MV.length mem - start) mem+ in do Just idx <- VStream.findIndex (== 0) (MV.mstream slice) -- todo error handling+ mutableEval ops mem (MemOffset $ start + idx)+ Scan Down offset ->+ let end = o2i $ pos + offset+ slice :: v (PrimState m) Int8+ slice = MV.slice 0 (end + 1) mem+ in do Just idx <- VStream.findIndex (== 0) (MV.mstreamR slice) -- todo error handling+ mutableEval ops mem (MemOffset $ end - idx)++o2i :: MemOffset -> Int+o2i = coerce++{-# INLINE o2i #-}+factor2i :: MulFactor -> Int8+factor2i = fromIntegral . (coerce :: MulFactor -> Int)++{-# INLINE factor2i #-}+-- | Size of the default VM memory, in bytes.+machineSize :: Word+machineSize = 30000++-- | A VM 'Machine' with the default memory available.+emptyMachine :: MachineType+emptyMachine = mkMachine machineSize++-- | Create a new machine with the given memory+mkMachine :: Word -> MachineType+mkMachine n = Machine {memory = GV.replicate (fromIntegral n) 0, pointer = 0}++-- | Command line arguments for the VM evaluator.+data VMOptions = VMOptions+ { vmOptsMemoryBytes :: Word -- ^ Available memory in bytes.+ , vmOptsDumpMemory :: Bool -- ^ Dump the contents of the memory after executing a program+ , vmOptsProgramPath :: FilePath -- ^ Path to the compiled program+ } deriving (Show)++-- | Default configuration for the VM.+defaultVMOptions :: VMOptions+defaultVMOptions =+ VMOptions+ { vmOptsMemoryBytes = 30000+ , vmOptsDumpMemory = False+ , vmOptsProgramPath = ""+ }++optionsP :: Parser VMOptions+optionsP =+ (\mem dump input ->+ VMOptions+ { vmOptsMemoryBytes = mem+ , vmOptsDumpMemory = dump+ , vmOptsProgramPath = input+ }) <$>+ option+ auto+ (long "memory" <> short 'm' <> metavar "BYTES" <>+ value (vmOptsMemoryBytes defaultVMOptions) <>+ help "Size of the memory [in bytes] used to run the program") <*>+ switch+ (long "dump-memory" <> short 'd' <>+ help "Dump the contents of the memory when the program is finished") <*>+ argument str (metavar "PROGRAM" <> help "Path to the compiled program")++parserInfo :: ParserInfo VMOptions+parserInfo =+ info+ (optionsP <**> helper)+ (fullDesc <> progDesc "Run the compiled Brainfuck program in PROGRAM file" <>+ header "An optimizing Brainfuck compiler and evaluator")++-- | Parse a list of command line arguments+parsePure :: [String] -> ParserResult VMOptions+parsePure = execParserPure defaultPrefs parserInfo++-- | Parse a list of command line arguments printing errors to the stderr+unsafeParse :: [String] -> IO VMOptions+unsafeParse = handleParseResult . parsePure++-- | Parse command line arguments printing errors to the stderr+parse :: IO VMOptions+parse = getArgs >>= unsafeParse
+ src/HBF/Parser.hs view
@@ -0,0 +1,91 @@+{-|+Description : Brainfuck parsing+Copyright : (c) Sebastian Galkin, 2018+License : GPL-3++Parsing 'Text' into 'Program' 'Unparsed'+-}+module HBF.Parser+ ( module HBF.Parser+ -- * Reexport from "Text.Parsec"+ , Text.Parsec.ParseError+ ) where++import Control.Applicative ((<|>))+import Data.Text.Lazy (Text)+import Text.Parsec (ParseError, between, eof, many, many1,+ runP)+import Text.Parsec.Char (char, noneOf, oneOf)+import Text.Parsec.Text.Lazy (Parser)++import HBF.Types++-- $setup+-- >>> :set -XOverloadedStrings+-- >>> import Data.Either+-- >>> let parse :: Parser a -> Text -> Either ParseError a; parse p text = runP p () "" text+++-- | Parser for a full 'Program'.+--+-- >>> isRight $ parse program " +[->>+ +[<] ##garbage## ],.[-] can ignore garbage"+-- True+program :: Parser (Program Unoptimized)+program = Program <$> many1 operation++-- | Parser for an 'Op', ignoring unknown characters.+--+-- >>> parse operation " +///"+-- Right (Inc 1 0)+--+-- >>> parse operation "fooo [+>] baaar "+-- Right (Loop [Inc 1 0,Move 1])+operation :: Parser Op+operation = many garbage *> (simpleOp <|> loopOp) <* many garbage++-- | The characters allowed in a Brainfuck program except for the loop characters @[@ and @]@.+bfSimpleTokens :: String+bfSimpleTokens = "><+-.,"++-- | The characters allowed in a Brainfuck program.+bfTokens :: String+bfTokens = "[]" ++ bfSimpleTokens++-- | Parser for unknown characters+--+-- >>> parse garbage "this is @#! garbage"+-- Right 't'+--+-- >>> isLeft $ parse garbage "+"+-- True+garbage :: Parser Char+garbage = noneOf bfTokens++-- | Parser for simple operations (not loops).+--+-- >>> parse simpleOp ">"+-- Right (Move 1)+--+-- >>> parse simpleOp "."+-- Right (Out 1 0)+simpleOp :: Parser Op+simpleOp = build <$> oneOf bfSimpleTokens+ where+ build '>' = Move 1+ build '<' = Move (-1)+ build '+' = Inc 1 0+ build '-' = Inc (-1) 0+ build '.' = Out 1 0+ build ',' = In 1 0+ build _ = error "Unknown character"++-- | Parser for loops.+--+-- >>> parse loopOp "[+-]"+-- Right (Loop [Inc 1 0,Inc (-1) 0])+loopOp :: Parser Op+loopOp = Loop . instructions <$> between (char '[') (char ']') program++-- | Parse program stream. Returns an error or the parsed 'Program'+parseProgram :: Text -> Either ParseError (Program Unoptimized)+parseProgram = runP (program <* eof) () ""
+ src/HBF/Types.hs view
@@ -0,0 +1,193 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE InstanceSigs #-}+{-# LANGUAGE RecordWildCards #-}++{-|+Description : Basic types for the Brainfuck compiler and virtual machine.+Copyright : (c) Sebastian Galkin, 2018+License : GPL-3++All the basic types for the Brainfuck compiler and VM are defined in this module.+This includes the different instructions ('Op's), the 'Program' and the 'MachineIO'.+-}+module HBF.Types where++import Control.DeepSeq (NFData)+import Control.Exception (catch)+import Control.Monad.Trans.State.Lazy (StateT, get, modify, put)+import Data.Binary (Binary)+import Data.Char (chr, ord)+import Data.Int (Int8)+import Data.List (uncons)+import Data.Semigroup (Semigroup (..))+import GHC.Generics (Generic)+import System.IO (hFlush, stdout)++-- * Virtual Machine Instructions+-- | Operations or instructions in the Brainfuck virtual machine.+--+-- Some of these operations are \"native\" to Brainfuck and others are the result of optimization during compilation.+-- The compiler generates these types of instructions and the virtual machine can execute them.+--+-- In all these instructions the 'MemOffset' represents a shift relative to the current position of the pointer.+-- The operation will refer and apply its action to this shifted position.+data Op+ -- | Increment by the amount specified by the @Int@+ = Inc {-# UNPACK #-}!Int+ {-# UNPACK #-}!MemOffset+ -- | Move the current pointer by the specified amount+ | Move {-# UNPACK #-}!MemOffset+ -- | Repeatedly read a byte into the machine and write the last one read to the shifted position.+ -- @n@ is usually 1 in real programs, but not always. Where the byte is read from will depend on the 'MachineIO' impleentation.+ | In {-# UNPACK #-}!Int+ {-# UNPACK #-}!MemOffset+ -- | Repeatedly write the byte in the shifted position. Where the byte is written will depend on the 'MachineIO' impleentation.+ | Out {-# UNPACK #-}!Int+ {-# UNPACK #-}!MemOffset+ -- | Native Brainfuck looping instruction.+ | Loop ![Op]+ -- | Optimized instruction. Set the shifted position to zero. In Brainfuck this is usually written as @[-]@+ | Clear {-# UNPACK #-}!MemOffset+ -- | Optimized instruction. Multiply by the factor the byte in the first @MemOffset@, writting to the second one.+ -- Second @MemOffset@ is relative to the first one. In brainfuck this is usually written as [->+<] and similar+ -- expressions.+ | Mul {-# UNPACK #-}!MulFactor+ {-# UNPACK #-}!MemOffset+ {-# UNPACK #-}!MemOffset+ -- | Find the nearest zero in the given direction, starting at the offset position. See 'Direction'.+ | Scan !Direction+ {-# UNPACK #-}!MemOffset+ deriving (Show, Eq, Generic, Binary, NFData)++-- | An offset into the Brainfuck VM memory. Positive numbers are in the direction of higher memory.+newtype MemOffset =+ MemOffset Int+ deriving (Generic)+ deriving newtype (Show, Eq, Num, Ord)+ deriving anyclass (Binary, NFData)++-- | A factor to multiply by in the 'Mul' instruction.+newtype MulFactor =+ MulFactor Int+ deriving (Generic)+ deriving newtype (Show, Eq, Num)+ deriving anyclass (Binary, NFData)++-- | A direction to 'Scan' for a memory position. 'Up' is in the direction of higher memory.+data Direction+ = Up -- ^ Scan in the direction of higher memory.+ | Down -- ^ Scan in the direction of lower memory.+ deriving (Show, Eq, Generic)+ deriving anyclass (Binary, NFData)++-- * Programs+-- | Marker type to distinguish optimized and 'Unoptimized' 'Program's.+data Optimized++-- | Marker type to distinguish 'Optimized' and unoptimized 'Program's.+data Unoptimized++-- | A list of 'Op's. 'opt' will be one of 'Optimized' or 'Unoptimized' to+-- distinguish both types of programs at the type level.+newtype Program opt = Program+ { instructions :: [Op] -- ^ The list of instructions in the program.+ } deriving (Generic) deriving newtype (Show, Eq) deriving anyclass ( Binary+ , NFData+ )++-- | Return the full list of instructions in a program, by unrolling 'Loop' instructions+-- into the list.+--+-- >>> flattened $ Program [Inc 1 0, Loop [Move 1, Scan Up 0]]+-- [Inc 1 0,Move 1,Scan Up 0]+flattened :: Program o -> [Op]+flattened p = [atom | op <- instructions p, atom <- atoms op]+ where+ atoms (Loop ops) = concatMap atoms ops+ atoms other = [other]++-- | Apply '<>' to the underlying @List@ of instructions.+instance Semigroup (Program o) where+ Program a <> Program b = Program $ a <> b++-- | The 'Monoid' of the underlying @List@ of instructions.+instance Monoid (Program o) where+ mappend = (<>)+ mempty = Program mempty++-- * Runtime State+-- | The state of a Brainfuck virtual machine.+data Machine v = Machine+ { memory :: v -- ^ The full memory of the machine. This will be a 'Data.Vector.Unboxed.Vector' or a List.+ , pointer :: MemOffset -- ^ The current execution pointer, information is written and read at this position.+ } deriving (Show, Eq)++-- * VM Input/Output+-- | Provide input and output to a Brainfuck virtual machine.+--+-- This class allows to run the VM in different monads, like 'IO' or 'StateT'.+class MachineIO m where+ putByte :: Int8 -> m () -- ^ Write the byte to the output of the VM.+ getByte :: m (Maybe Int8) -- ^ Read a byte from the input of the VM. If @EOF@ has been reached, return 'Nothing'++-- | 'IO' takes its input and output from stdin/stdout+instance MachineIO IO where+ putByte = putChar . toEnum . fromIntegral+ getByte = fmap (fromIntegral . fromEnum) <$> (hFlush stdout >> safeGetChar)+ where+ safeGetChar = fmap Just getChar `catch` recover+ recover :: IOError -> IO (Maybe Char)+ recover _ = return Nothing++-- * Test Helpers+-- | A data structure for mocking input and output to the VM. This can be used to run the VM+-- in a 'StateT' monad for testing purposes.+data MockIO = MockIO+ { machineIn :: [Int8]+ -- ^ Every time the machine executes an 'In' instruction, input will be taken from this list.+ , machineOut :: [Int8]+ -- ^ Every time the machine executes an 'Out' instruction, output will be put into this list, in LIFO order.+ } deriving (Show, Eq, Generic, NFData)++-- | Create a 'MockIO' that will have the given input available.+mkMockIO :: [Int8] -> MockIO+mkMockIO input = MockIO {machineIn = input, machineOut = []}++-- | Create a 'MockIO' that will have the given input available. ASCII encoding.+mkMockIOS :: String -> MockIO+mkMockIOS = mkMockIO . map (fromIntegral . ord)++-- | Get the output after a VM has ran using this 'MockIO'.+mockOutput :: MockIO -> [Int8]+mockOutput = reverse . machineOut++-- | Get the output after a VM has ran using this 'MockIO'. ASCII encoding.+mockOutputS :: MockIO -> String+mockOutputS = map (chr . fromIntegral) . mockOutput++-- | 'StateT' takes its input and output from the lists inside the 'MockIO'.+instance Monad m => MachineIO (StateT MockIO m) where+ putByte :: Int8 -> StateT MockIO m ()+ putByte b = modify update+ where+ update st@MockIO {..} = st {machineOut = b : machineOut}+ getByte :: StateT MockIO m (Maybe Int8)+ getByte = do+ st@MockIO {..} <- get+ maybe (pure Nothing) (update st) $ uncons machineIn+ where+ update st (b, bs) = put st {machineIn = bs} >> return (Just b)++-- * Helper Functions+-- | '<$>' with arguments reversed.+(<&>) :: Functor f => f a -> (a -> b) -> f b+(<&>) = flip (<$>)++-- | Helper function to convert a 'Right' into a 'Just' and a 'Left' into a 'Nothing'.+eitherToMaybe :: Either a b -> Maybe b+eitherToMaybe (Right b) = Just b+eitherToMaybe (Left _) = Nothing
+ src/exe/hbf/Main.hs view
@@ -0,0 +1,12 @@+module Main where++import HBF.Compiler (loadFile)+import HBF.Eval (VMOptions (..), evalWithIO, parse)+import System.IO (hFlush, stdout)++main :: IO ()+main = do+ vmOpts <- parse+ program <- loadFile (vmOptsProgramPath vmOpts)+ _ <- evalWithIO vmOpts program+ hFlush stdout
+ src/exe/hbfc/Main.hs view
@@ -0,0 +1,20 @@+module Main where++import Data.Monoid ((<>))+import System.Exit (die)++import HBF.Compiler (CompilationSummary, ParseError, compile, parse)++main :: IO ()+main = do+ compilerOpts <- parse+ res <- compile compilerOpts+ either errorOut successOut res++errorOut :: ParseError -> IO ()+errorOut err = do+ putStrLn "Error compiling code"+ die (show err)++successOut :: CompilationSummary -> IO ()+successOut s = putStrLn $ "Compiled code:\n" <> show s
+ tests/CompilerTest.hs view
@@ -0,0 +1,204 @@+module CompilerTest where++import Control.Monad.Trans.State (execStateT)+import qualified Data.Text.Lazy.IO as TIO+import Hedgehog+import qualified Hedgehog as H+import Hedgehog.Checkers as HC+import Test.HUnit++import HBF.Compiler+import qualified HBF.Eval as E+import HBF.Types+import Helper++unit_fusionOptimization :: Assertion+unit_fusionOptimization = fusionOpt (Program p) @?= Program expected+ where+ p =+ [ Inc 2 1+ , Inc (-1) 1+ , Move 3+ , Move (-1)+ , Inc 1 0+ , In 1 0+ , In 2 0+ , Out 3 0+ , Out 4 0+ , Inc 2 0+ , Inc (-2) 0 -- should eliminate this+ , Out 1 0 --should not fuse the next two, but should fuse this one with the previous Out+ , Out 1 1+ , Out 1 2+ , Loop+ [ Inc 1 0+ , Inc 2 0+ , Loop [Move 1, Move 2, Clear 0, Clear 0, Clear 1, Clear 2]+ , Loop [Move 1, Move (-1)] -- should eliminate this whole loop+ , Scan Up 0+ , Scan Up 0+ , Scan Down 3+ , Scan Down 3+ , Scan Up 0 -- shouldn't fuse the next two+ , Scan Up 3+ , Scan Down 0 -- shouldn't fuse the next two+ , Scan Down 3+ ]+ ]+ expected =+ [ Inc 1 1+ , Move 2+ , Inc 1 0+ , In 3 0+ , Out 8 0+ , Out 1 1+ , Out 1 2+ , Loop+ [ Inc 3 0+ , Loop [Move 3, Clear 0, Clear 1, Clear 2]+ , Scan Up 0+ , Scan Down 3+ , Scan Up 0+ , Scan Up 3+ , Scan Down 0+ , Scan Down 3+ ]+ ]++unit_optimizationsDontChangeResults :: Assertion+unit_optimizationsDontChangeResults = do+ code <- TIO.readFile "tests/factor.bf"+ let (Right (optimized, _)) = inMemoryCompile defaultCompilerOptions code+ let (Right (unoptimized, _)) =+ inMemoryCompile noOptimizationCompilerOptions code+ a <- exec optimized+ b <- exec unoptimized+ a @?= b+ where+ exec program = execStateT (E.eval program) (mkMockIOS "25454\n")++fullyFused :: Program o -> Bool+fullyFused p = all (uncurry fused) (zip ops (tail ops))+ where+ ops = instructions p+ fused (Inc _ n) (Inc _ m)+ | n == m = False+ fused (Move _) (Move _) = False+ fused (In _ n) (In _ m)+ | n == m = False+ fused (Out _ n) (Out _ m)+ | n == m = False+ fused (Clear n) (Clear m)+ | n == m = False+ fused (Loop inner) _ = fullyFused $ Program inner+ fused _ (Loop inner) = fullyFused $ Program inner+ fused _ _ = True++unit_fullyFusedTest :: Assertion+unit_fullyFusedTest =+ not (fullyFused $ Program [Inc 1 1, Inc 4 1]) &&+ not (fullyFused $ Program [Inc 1 0, Loop [Inc 1 1, Loop [Move 1, Move 2]]]) &&+ fullyFused (Program [Inc 1 0, Move 2]) @=? True++hprop_fusionDoesntLeaveAnythingToBeFused :: Property+hprop_fusionDoesntLeaveAnythingToBeFused =+ property $ do+ program <- forAll programGen+ let optimized = fusionOpt . toIR $ program+ H.assert $ all noNoOp (flattened optimized) && fullyFused optimized+ where+ noNoOp (Inc n _) = n /= 0+ noNoOp (Move n) = n /= 0+ noNoOp (In n _) = n /= 0+ noNoOp (Out n _) = n /= 0+ noNoOp (Clear _) = True+ noNoOp (Mul _ _ to) = to /= 0+ noNoOp (Scan _ _) = True+ noNoOp (Loop _) = error "noNoOp: unexpected operation"++hprop_FusedProgramHasValidMonoid :: Property+hprop_FusedProgramHasValidMonoid = property $ HC.monoid programGen++unit_clearOptimization :: Assertion+unit_clearOptimization = clearOpt (Program p) @?= Program expected+ where+ p =+ [ Inc 2 0+ , Inc (-1) 0+ , Loop [Inc (-1) 0]+ , Loop+ [ Inc 1 0+ , Loop [Inc (-1) 0]+ , Loop [Loop [Inc (-1) 0], Move 3, Loop [Inc (-1) 0]]+ ]+ ]+ expected =+ [ Inc 2 0+ , Inc (-1) 0+ , Clear 0+ , Loop [Inc 1 0, Clear 0, Loop [Clear 0, Move 3, Clear 0]]+ ]++unit_mulOptimization :: Assertion+unit_mulOptimization = mulOpt (Program p) @?= Program expected+ where+ p =+ [ Inc 2 0+ , Inc (-1) 0+ , makeMul [(1, 2)]+ , Loop [Inc (-1) 0, makeMul [(2, 4), (4, 5)], Inc 1 0]+ , Loop [Inc (-1) 0, Move 1, Inc 1 0, Move (-1), Inc 1 0] {- this extra part breaks the multiplication loop -}+ -- this tests missing eof+ ]+ expected =+ [ Inc 2 0+ , Inc (-1) 0+ , Mul 1 0 2+ , Clear 0+ , Loop [Inc (-1) 0, Mul 2 0 4, Mul 4 0 9, Clear 0, Inc 1 0]+ , Loop [Inc (-1) 0, Move 1, Inc 1 0, Move (-1), Inc 1 0]+ ]++unit_scanOptimization :: Assertion+unit_scanOptimization = scanOpt (Program p) @?= Program expected+ where+ p =+ [ Inc 2 0+ , Inc (-1) 0+ , Loop [Move (-1)]+ , Loop [Inc (-1) 0, Loop [Move 1], Loop [Move 2], Inc 1 0]+ ]+ expected =+ [ Inc 2 0+ , Inc (-1) 0+ , Scan Down 0+ , Loop [Inc (-1) 0, Scan Up 0, Loop [Move 2], Inc 1 0]+ ]++unit_offsetInstructionsOptimization :: Assertion+unit_offsetInstructionsOptimization =+ offsetInstructionOpt (Program p) @?= Program expected+ where+ p =+ [ Inc 2 0+ , Move 1+ , Inc (-1) 0+ , Move 2+ , Mul 3 0 2+ , Loop [Move (-1)]+ , Loop+ [ Inc (-1) 0+ , Move (-1)+ , In 1 0+ , Loop [Move 2, Inc 3 0, Move (-1)]+ , Inc 1 0+ ]+ ]+ expected =+ [ Inc 2 0+ , Inc (-1) 1+ , Mul 3 3 2+ , Move 3+ , Loop [Move (-1)]+ , Loop [Inc (-1) 0, In 1 (-1), Move (-1), Loop [Inc 3 2, Move 1], Inc 1 0]+ ]
+ tests/EvalTest.hs view
@@ -0,0 +1,89 @@+module EvalTest where++import Control.Monad.Trans.State (runStateT)+import Data.Char (ord)+import Data.Int (Int8)+import qualified Data.Text.Lazy.IO as TIO+import qualified Data.Vector.Generic as GV+import Test.HUnit+import Test.SmallCheck++import qualified HBF.Compiler as C+import qualified HBF.Eval as E+import HBF.Types+import Helper++unit_canFactorNumbers :: Assertion+unit_canFactorNumbers = do+ (_, out) <- execFile "tests/factor.bf" "25454\n"+ out @?= "25454: 2 11 13 89\n"++unit_evalScanR :: Assertion+unit_evalScanR = do+ (machine, _) <- execProgramS program ""+ let (Machine mem index) = listMachine machine+ (index, take 6 mem) @?= (4, [42, 42, 42, 42, 17, 0])+ where+ program -- evaluating should give [42,42,42,42,17,0,...]+ = Program [Inc 42 0, Mul 1 0 1, Mul 1 0 2, Mul 1 0 3, Scan Up 0, Inc 17 0]++unit_evalScanL :: Assertion+unit_evalScanL = do+ (machine, _) <- execProgramS program ""+ let (Machine mem index) = listMachine machine+ (index, take 6 mem) @?= (1, [0, 17, 42, 42, 42, 0])+ where+ program -- evaluating should give [0,17,42,42,42,0,...]+ = Program [Move 2, Inc 42 0, Mul 1 0 1, Mul 1 0 2, Scan Down 0, Inc 17 0]++unit_evalScanROnZero :: Assertion+unit_evalScanROnZero = do+ (machine, _) <- execProgramS program ""+ let (Machine mem index) = listMachine machine+ (index, take 4 mem) @?= (1, [42, 0, 42, 0])+ where+ program -- evaluating should give [42,0,42,0,...]+ = Program [Inc 42 0, Move 2, Inc 42 0, Move (-1), Scan Up 0]++unit_evalScanLOnZero :: Assertion+unit_evalScanLOnZero = do+ (machine, _) <- execProgramS program ""+ let (Machine mem index) = listMachine machine+ (index, take 4 mem) @?= (1, [42, 0, 42, 0])+ where+ program -- evaluating should give [42,0,42,0,...]+ = Program [Inc 42 0, Move 2, Inc 42 0, Move (-1), Scan Down 0]++-- todo: implement a property test starting with arbitrary memory+-- and evaluating ScanR and ScanL+scprop_allOptimizationFlagsSameResult :: CompFlags -> Property IO+scprop_allOptimizationFlagsSameResult (CompFlags opts) =+ monadic $ do+ code <- TIO.readFile "tests/allfeatures.bf"+ let (Right (program, _)) = C.inMemoryCompile opts code+ (finalMachine, finalState) <- execProgram program (mkMockIOS "0")+ pure $+ mockOutputS finalState == expectedOutput &&+ memory finalMachine == expectedMemory+ where+ expectedOutput = "AABFAq"+ expectedMemory =+ memory E.emptyMachine GV.//+ zip [0 ..] [fromIntegral (ord '0' + ord 'A') :: Int8, 0, 0, 0, 1, 1, 70]++unit_evalWithSmallMemory :: Assertion+unit_evalWithSmallMemory = do+ code <- TIO.readFile "tests/allfeatures.bf"+ let (Right (program, _)) = C.inMemoryCompile C.defaultCompilerOptions code+ (finalMachine, finalState) <-+ runStateT+ (E.evalWith E.defaultVMOptions {E.vmOptsMemoryBytes = bytes} program)+ (mkMockIOS "0")+ mockOutputS finalState @?= expectedOutput+ memory finalMachine @?= expectedMemory+ where+ bytes = 7 :: Word+ expectedOutput = "AABFAq"+ expectedMemory =+ memory (E.mkMachine bytes) GV.//+ zip [0 ..] [fromIntegral (ord '0' + ord 'A') :: Int8, 0, 0, 0, 1, 1, 70]
+ tests/Helper.hs view
@@ -0,0 +1,139 @@+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE OverloadedStrings #-}++-- needed for smallcheck+module Helper where++import Control.Monad.Trans.State (runStateT)+import Data.Coerce (coerce)+import Data.Int (Int8)+import Data.Semigroup ((<>))+import Data.Text.Lazy (Text, pack)+import qualified Data.Text.Lazy.IO as TIO+import qualified Data.Vector.Unboxed as Vector+import Hedgehog (Gen)+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.SmallCheck.Series++import HBF.Compiler (CompilerOptions (..),+ defaultCompilerOptions,+ inMemoryCompile)+import HBF.Eval (MachineType, eval)+import HBF.Parser+import HBF.Types++basicOpCharGen :: Gen Char+basicOpCharGen = Gen.element bfSimpleTokens++commentCodeGen :: Gen Char+commentCodeGen = Gen.filter (not . flip elem bfTokens) Gen.unicode++basicCodeGen :: Gen Text+basicCodeGen = pack <$> Gen.filter hasCode strings+ where+ chars = Gen.frequency [(5, basicOpCharGen), (2, commentCodeGen)]+ strings = Gen.list (Range.linear 1 100) chars+ hasCode :: String -> Bool+ hasCode = any (`elem` bfSimpleTokens)++loopGen :: Gen Text+loopGen = fmap (\code -> "[" <> code <> "]") codeGen++codeGen :: Gen Text+codeGen = (<>) <$> block <*> block+ where+ block = Gen.frequency [(10, basicCodeGen), (1, loopGen)]++programGen :: Gen (Program Unoptimized)+programGen =+ Program . concat <$>+ Gen.list+ (Range.linear 0 120)+ (Gen.recursive weights [basic] [(: []) . Loop . instructions <$> programGen])+ where+ basic :: Gen [Op]+ basic =+ Gen.frequency+ [ (100, pure [Inc 1 0])+ , (50, pure [Inc (-1) 0])+ , (80, pure [Move (-1)])+ , (70, pure [Move 1])+ , (5, pure [Out 1 0])+ , (2, pure [In 1 0])+ , (10, (\b -> b ++ b) <$> basic) --fusable+ , (3, pure [Loop [Move (-1)]]) --scanL+ , (2, pure [Loop [Move 1]]) --scanR+ , (1, pure [Loop [Inc (-1) 0]]) --clear loop+ , ( 1+ , pure+ [ Inc (-1) 0+ , Move 1+ , Inc 1 0+ , Inc 1 0+ , Move 1+ , Move 1+ , Inc (-1) 0+ , Move (-1)+ , Move (-1)+ ]) --mul loop --fixme use makeMul+ ]+ weights [nonrec] = nonrec+ weights (nonrec:recursive:_) = Gen.frequency [(10, nonrec), (1, recursive)]+ weights [] = error "programGen: unexpected condition"++makeMul :: [(MulFactor, MemOffset)] -> Op+makeMul muls =+ Loop $+ (Inc (-1) 0 : concatMap mkMul muls) +++ replicate (coerce $ sum $ map snd muls) (Move (-1))+ where+ mkMul (MulFactor fact, MemOffset off) =+ replicate off (Move 1) ++ replicate fact (Inc 1 0)++listMachine :: Machine (Vector.Vector Int8) -> Machine [Int8]+listMachine t = t {memory = Vector.toList (memory t)}++newtype CompFlags =+ CompFlags CompilerOptions+ deriving (Show)++instance Monad m => Serial m CompFlags where+ series =+ cons5+ (\a b c d e ->+ CompFlags+ CompilerOptions+ { cOptsOut = Nothing+ , cOptsFusionOptimization = a+ , cOptsClearLoopOptimization = b+ , cOptsMulOptimization = c+ , cOptsScanOptimization = d+ , cOptsOffsetInstructionsOptimization = e+ , cOptsVerbose = False+ , cOptsSource = ""+ })++cons5 ::+ (Serial m a5, Serial m a4, Serial m a3, Serial m a2, Serial m a1)+ => (a1 -> a2 -> a3 -> a4 -> a5 -> a6)+ -> Series m a6+cons5 f = decDepth $ f <$> series <~> series <~> series <~> series <~> series++execProgram :: Program Optimized -> MockIO -> IO (MachineType, MockIO)+execProgram p = runStateT (eval p)++execProgramS :: Program Optimized -> String -> IO (MachineType, MockIO)+execProgramS p input = runStateT (eval p) (mkMockIOS input)++execCodeMock :: Text -> String -> IO (MachineType, MockIO)+execCodeMock code input = execProgram p (mkMockIOS input)+ where+ (Right (p, _)) = inMemoryCompile defaultCompilerOptions code++execCode :: Text -> String -> IO (MachineType, String)+execCode code input = fmap mockOutputS <$> execCodeMock code input++execFile :: FilePath -> String -> IO (MachineType, String)+execFile p input = TIO.readFile p >>= \code -> execCode code input
+ tests/IntegrationTests.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE OverloadedStrings #-}++module IntegrationTests where++import Control.Monad.Trans.State (execStateT)+import System.IO (hClose)+import System.IO.Temp (withSystemTempFile)+import Test.HUnit++import qualified HBF.Compiler as C+import qualified HBF.Eval as E+import HBF.Types++squaresPath :: FilePath+squaresPath = "tests/squares.bf"++squaresResult :: String+squaresResult = concatMap ((++ "\n") . show) sq+ where+ sq :: [Int]+ sq = takeWhile (<= 10000) $ map (\n -> n * n) [0 ..]++compile :: FilePath -> IO (Program Optimized)+compile inpath =+ withSystemTempFile "hbftests.bfc" $ \outpath handle -> do+ hClose handle+ cOpts <- C.unsafeParse ["--output", outpath, inpath]+ Right _ <- C.compile cOpts+ C.loadFile outpath++unit_compileAndEvalSquares :: Assertion+unit_compileAndEvalSquares = do+ program <- compile squaresPath+ mock <- execStateT (E.eval program) (mkMockIO [])+ mockOutputS mock @?= squaresResult
+ tests/ParserTest.hs view
@@ -0,0 +1,42 @@+{-# LANGUAGE OverloadedStrings #-}++module ParserTest where++import Data.Either (isLeft, isRight)+import Data.Semigroup ((<>))+import Hedgehog+import qualified Hedgehog as H+import qualified Hedgehog.Gen as Gen+import Test.HUnit+import qualified Test.HUnit as HU++import HBF.Parser+import HBF.Types+import Helper++unit_parseBasicProgram :: Assertion+unit_parseBasicProgram =+ parseProgram "+><-[+,.[-]<<]" @?= Right (Program result)+ where+ result =+ [ Inc 1 0+ , Move 1+ , Move (-1)+ , Inc (-1) 0+ , Loop [Inc 1 0, In 1 0, Out 1 0, Loop [Inc (-1) 0], Move (-1), Move (-1)]+ ]++unit_cantParseEmpty :: Assertion+unit_cantParseEmpty = HU.assert $ isLeft $ parseProgram ""++hprop_parseRandomPrograms :: Property+hprop_parseRandomPrograms =+ property $ forAll codeGen >>= H.assert . isRight . parseProgram++hprop_cantParseUnbalancedLoop :: Property+hprop_cantParseUnbalancedLoop =+ property $ do+ p1 <- forAll $ Gen.frequency [(10, codeGen), (1, Gen.constant "")]+ p2 <- forAll $ Gen.frequency [(10, codeGen), (1, Gen.constant "")]+ braket <- forAll $ Gen.element ["[", "]"]+ H.assert $ isLeft $ parseProgram (p1 <> braket <> p2)
+ tests/allfeatures.bf view
@@ -0,0 +1,86 @@+write a number 65 in position 1 by multiplying 6 by 10 and adding 5++++++++ this is a 6+[->++++++++++ (10 times)<] a multiplication loop++> +++++++at this point memory should be (0 65# 0 0 0 etc)++print an A++.++> > + > + > +-+++(0 65 0 1 1 1# 0 0 etc)++[<]++(0 65 0# 1 1 1 0 0 etc)++copy twice the 65 before++<+[->+>+<<]++(0 0# 65 66 1 1 0 0 etc)++Print A and B+>.>.++move to the first 0 to the right+[>]++(0 0 65 66 1 1 0# 0 etc)++put a negative by adding 128 and wrapping+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++multiply the 66 by 3 putting in the zero++<<<+[->>>+++<<<]+++(0 0 65 0# 1 1 70 0 etc)++>>>++print F+.++[<]+<++print A+.++(0 0 65# 0 1 1 70 0 etc)++get some data+<,++add it to 65 in position 0++[-<+>]+>+[-<<+>>]+++(65 plus x 0 0# 0 1 1 70 0 etc)++print the result (if a 0 was the input it should print a q (48 plus 65)+<<.
+ tests/doctest.hs view
@@ -0,0 +1,4 @@+import Test.DocTest++main :: IO ()+main = doctest ["-isrc", "src/HBF"]
+ tests/factor.bf view
@@ -0,0 +1,195 @@+* factor an arbitrarily large positive integer+*+* Copyright (C) 1999 by Brian Raiter+* under the GNU General Public License++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>-++*+* read in the number+*++<<<<<<<<<++[-[>>>>>>>>>>][-]<<<<<<<<<<[[->>>>>>>>>>+<<<<<<<<<<]<<<<<<<<<<]+ >>>>>>>>>>,----------]+>>>>>>>>>>[------------------------------------->>>>>>>>>->]+<[+>[>>>>>>>>>+>]<-<<<<<<<<<<]-++*+* display the number and initialize the loop variable to two+*++[>++++++++++++++++++++++++++++++++++++++++++++++++.+ ------------------------------------------------<<<<<<<<<<<]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+--------------------------.[-]+>>>>>>>>>>>>++<<<<+++*+* the main loop+*++[ [-]>>++ *+ * make copies of the number and the loop variable+ *++ [>>>>[-]>[-]>[-]>[-]+ >[-]>[-]+ <<<<<<<[->>>+>+<<<<]>>>>>>>>]+ <<<<<<<<<<[>>>>>>[-<<<<+>>>>]<<<<<<<<<<<<<<<<]>>>>>>>>>>+ [>[->>>+>>+<<<<<]>>>>>>>>>]+ <<<<<<<<<<[>>>>>>[-<<<<<+>>>>>]<<<<<<<<<<<<<<<<]>>>>>>>>>>++ *+ * divide the number by the loop variable+ *++ [>>>[-]>>>[-]>[-]>>>] initialize+ <<<<<<<<<<[<<<<<<<<<<]+ >>>>>>>>>[-]>>>>>>>+<<<<<<<<[+]++ [ ->> double divisor until above dividend+ [>>>>>>[->++<]>>>>]<<<<<<<<<<+ [>>>>>>>>[-]>[-]+ <<<<[->>>++<<<]<<<<<<<<<<<<<<<]>>>>>>>>>>+ [>>>>>>>>[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<+ [->--------->>>>>>>>>+<<<<<<<<<<[->+<]]]]]]]]]]]>>]+ <<<<<<<<<<[>>>>>>>>>[-<+<<<+>>>>]<<<<<<<<<<<<<<<<<<<]>>>>>>>>>>+ [>>>>>>>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>+ [-<--------->>>>>>>>>>>+<<<<<<<<<<[-<+>]]]]]]]]]]]>>>]+ <<<<<<<<<<+ [>>>>[->>>+>>+<<<<<]<<<<<<<<<<<<<<]+ >>>>>>>>>>[>>>>>>>[-<<<+>>>]>>>]<<<<<<<<<<+ [>>>>>>>>[->-<]>+ [<<<<<<<<<[<[-]>>>>>>>>>>[-<<<<<<<<<<+>>>>>>>>>>]<<<<<<<<<<<<<<<<<<<]+ >>>>>>>>>>>>>>>>>>>]+ <<<<<<<<<<<<<<<<<<<]+ >>>>>>>>>[+[+[+[+[+[+[+[+[+[+[[-]<+>]]]]]]]]]]]<+ ]+ >>>>>>>>+ [ subtract divisor from dividend+ <<<<<<+ [>>>>>>>>[-]>[-]<<<<<[->>>+>+<<<<]>>>>>>]<<<<<<<<<<+ [>>>>>>>>[-<<<<+>>>>]<<<[->>>+>+<<<<]<<<<<<<<<<<<<<<]>>>>>>>>>>+ [>>>>>>>>>[-<<<<+>>>>]>]<<<<<<<<<<+ [>>>>>>>>[-<->]<<<<<<<<<<<<<<<<<<]>>>>>>>>>>+ [>>>>>>>[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<+ [++++++++++[+>-<]>>>>>>>>>>-<<<<<<<<<<]]]]]]]]]]]>>>]+ >>>>>>>++ [ if difference is nonnegative then+ [-]<<<<<<<<<<<<<<<<< replace dividend and increment quotient+ [>>>>[-]>>>>[-<<<<+>>>>]<<[->>+<<]<<<<<<<<<<<<<<<<]>>>>>>>>>>+ [>>>>>>>>[->+<<<+>>]>>]<<<<<<<<<<+ [>>>[->>>>>>+<<<<<<]<<<<<<<<<<<<<]>>>>>>>>>>+ [>>>>>>>>>[-<<<<<<+>>>>>>[-<<<<<<+>>>>>>+ [-<<<<<<+>>>>>>[-<<<<<<+>>>>>>+ [-<<<<<<+>>>>>>[-<<<<<<+>>>>>>+ [-<<<<<<+>>>>>>[-<<<<<<+>>>>>>+ [-<<<<<<+>>>>>>[-<<<<<<--------->>>>>>>>>>>>>>>>+<<<<<<<<<<+ [-<<<<<<+>>>>>>]]]]]]]]]]]>]+ >>>>>>>+ ] halve divisor and loop until zero+ <<<<<<<<<<<<<<<<<[<<<<<<<<<<]>>>>>>>>>>+ [>>>>>>>>[-]<<[->+<]<[->>>+<<<]>>>>>]<<<<<<<<<<+ [+>>>>>>>[-<<<<<<<+>>>>>>>[-<<<<<<<->>>>>>+>+ [-<<<<<<<+>>>>>>>[-<<<<<<<->>>>>>+>+ [-<<<<<<<+>>>>>>>[-<<<<<<<->>>>>>+>+ [-<<<<<<<+>>>>>>>[-<<<<<<<->>>>>>+>+ [-<<<<<<<+>>>>>>>]]]]]]]]]<<<<<<<+ [->>>>>>>+<<<<<<<]-<<<<<<<<<<]+ >>>>>>>+ [-<<<<<<<<<<<+>>>>>>>>>>>]+ >>>[>>>>>>>[-<<<<<<<<<<<+++++>>>>>>>>>>>]>>>]<<<<<<<<<<+ [+>>>>>>>>[-<<<<<<<<+>>>>>>>>[-<<<<<<<<->>>>>+>>>+ [-<<<<<<<<+>>>>>>>>[-<<<<<<<<->>>>>+>>>+ [-<<<<<<<<+>>>>>>>>[-<<<<<<<<->>>>>+>>>+ [-<<<<<<<<+>>>>>>>>[-<<<<<<<<->>>>>+>>>+ [-<<<<<<<<+>>>>>>>>]]]]]]]]]<<<<<<<<+ [->>>>>>>>+<<<<<<<<]-<<<<<<<<<<]+ >>>>>>>>[-<<<<<<<<<<<<<+>>>>>>>>>>>>>]>>+ [>>>>>>>>[-<<<<<<<<<<<<<+++++>>>>>>>>>>>>>]>>]<<<<<<<<<<+ [<<<<<<<<<<]>>>>>>>>>>+ >>>>>>+ ]+ <<<<<<++ *+ * make copies of the loop variable and the quotient+ *++ [>>>[->>>>+>+<<<<<]>>>>>>>]+ <<<<<<<<<<+ [>>>>>>>[-<<<<+>>>>]<<<<<[->>>>>+>>+<<<<<<<]<<<<<<<<<<<<]+ >>>>>>>>>>[>>>>>>>[-<<<<<+>>>>>]>>>]<<<<<<<<<<++ *+ * break out of the loop if the quotient is larger than the loop variable+ *++ [>>>>>>>>>[-<->]<+ [<<<<<<<<+ [<<[-]>>>>>>>>>>[-<<<<<<<<<<+>>>>>>>>>>]<<<<<<<<<<<<<<<<<<]+ >>>>>>>>>>>>>>>>>>]<<<<<<<<<<<<<<<<<<]+ >>>>>>>>[>-<[+[+[+[+[+[+[+[+[+[[-]>+<]]]]]]]]]]]>+++ [ [-]++ *+ * partially increment the loop variable+ *++ <[-]+>>>>+>>>>>>>>[>>>>>>>>>>]<<<<<<<<<<++ *+ * examine the remainder for nonzero digits+ *++ [<<<<<<[<<<<[<<<<<<<<<<]>>>>+<<<<<<<<<<]<<<<]+ >>>>>>>>>>>>>>>>>>>>[>>>>>>>>>>]<<<<<<<<<<[<<<<<<<<<<]+ >>>>-++ [ [+]++ *+ * decrement the loop variable and replace the number with the quotient+ *++ >>>>>>>>-<<[>[-]>>[-<<+>>]>>>>>>>]<<<<<<<<<<++ *+ * display the loop variable+ *++ [+>>[>>>>>>>>+>>]<<-<<<<<<<<<<]-+ [>>++++++++++++++++++++++++++++++++++++++++++++++++.+ ------------------------------------------------<<<<<<<<<<<<]+ ++++++++++++++++++++++++++++++++.[-]>>>>++ ]++ *+ * normalize the loop variable+ *++ >>>>>>+ [>>[->>>>>+<<<<<[->>>>>+<<<<<+ [->>>>>+<<<<<[->>>>>+<<<<<+ [->>>>>+<<<<<[->>>>>+<<<<<+ [->>>>>+<<<<<[->>>>>+<<<<<+ [->>>>>+<<<<<[->>>>>--------->>>>>+<<<<<<<<<<+ [->>>>>+<<<<<]]]]]]]]]]]>>>>>>>>]+ <<<<<<<<<<[>>>>>>>[-<<<<<+>>>>>]<<<<<<<<<<<<<<<<<]+ >>>>>>>>>++ ]<++]>>++*+* display the number and end+*++[>>>>>>>>>>]<<<<<<<<<<[+>[>>>>>>>>>+>]<-<<<<<<<<<<]-+[>++++++++++++++++++++++++++++++++++++++++++++++++.<<<<<<<<<<<]+++++++++++.
+ tests/squares.bf view
@@ -0,0 +1,8 @@+++++[>+++++<-]>[<+++++>-]+<+[+ >[>+>+<<-]++>>[<<+>>-]>>>[-]++>[-]++ >>>+[[-]++++++>>>]<<<[[<++++++++<++>>-]+<.<[>----<-]<]+ <<[>>>>>[>>>[-]+++++++++<[>-<-]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-+]+[Outputs square numbers from 0 to 10000.+Daniel B Cristofani (cristofdathevanetdotcom)+http://www.hevanet.com/cristofd/brainfuck/]
+ tests/test.hs view
@@ -0,0 +1,1 @@+{-# OPTIONS_GHC -F -pgmF tasty-discover #-}