From b13094106b7d98371d84bac1433b2e53665dccb0 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Thu, 26 Mar 2026 03:06:17 +0300 Subject: [PATCH 01/28] Initial commit --- Lazarev/.gitignore | 6 + Lazarev/.ocamlformat | 2 + Lazarev/.zanuda | 1 + Lazarev/COPYING | 674 ++++++++++++++++++++++++++++++++++ Lazarev/COPYING.CC0 | 121 ++++++ Lazarev/COPYING.LESSER | 165 +++++++++ Lazarev/Lazarev.opam | 41 +++ Lazarev/Lazarev.opam.template | 4 + Lazarev/Makefile | 49 +++ Lazarev/dune | 7 + Lazarev/dune-project | 39 ++ 11 files changed, 1109 insertions(+) create mode 100644 Lazarev/.gitignore create mode 100644 Lazarev/.ocamlformat create mode 100644 Lazarev/.zanuda create mode 100644 Lazarev/COPYING create mode 100644 Lazarev/COPYING.CC0 create mode 100644 Lazarev/COPYING.LESSER create mode 100644 Lazarev/Lazarev.opam create mode 100644 Lazarev/Lazarev.opam.template create mode 100644 Lazarev/Makefile create mode 100644 Lazarev/dune create mode 100644 Lazarev/dune-project diff --git a/Lazarev/.gitignore b/Lazarev/.gitignore new file mode 100644 index 00000000..7102a822 --- /dev/null +++ b/Lazarev/.gitignore @@ -0,0 +1,6 @@ +_build +_coverage +/_esy +/node_modules +/esy.lock +/.melange.eobjs diff --git a/Lazarev/.ocamlformat b/Lazarev/.ocamlformat new file mode 100644 index 00000000..97f97080 --- /dev/null +++ b/Lazarev/.ocamlformat @@ -0,0 +1,2 @@ +profile=janestreet +version=0.26.2 diff --git a/Lazarev/.zanuda b/Lazarev/.zanuda new file mode 100644 index 00000000..0f09b19b --- /dev/null +++ b/Lazarev/.zanuda @@ -0,0 +1 @@ +forward mutability_check ignore REPL.ml diff --git a/Lazarev/COPYING b/Lazarev/COPYING new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/Lazarev/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Lazarev/COPYING.CC0 b/Lazarev/COPYING.CC0 new file mode 100644 index 00000000..0e259d42 --- /dev/null +++ b/Lazarev/COPYING.CC0 @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/Lazarev/COPYING.LESSER b/Lazarev/COPYING.LESSER new file mode 100644 index 00000000..0a041280 --- /dev/null +++ b/Lazarev/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/Lazarev/Lazarev.opam b/Lazarev/Lazarev.opam new file mode 100644 index 00000000..80fcc513 --- /dev/null +++ b/Lazarev/Lazarev.opam @@ -0,0 +1,41 @@ +# This file is generated by dune, edit dune-project instead +opam-version: "2.0" +version: "0.1" +synopsis: "An interpreter for ML-like language" +description: "TODO" +maintainer: ["Andrey Lazarev "] +authors: ["Andrey Lazarev "] +license: "LGPL-3.0-or-later WITH OCaml-LGPL-linking-exception" +homepage: "https://github.com/Kakadu/fp25" +doc: "https://kakadu.github.io/fp25/docs/Lambda" +bug-reports: "https://github.com/Kakadu/fp25" +depends: [ + "dune" {>= "3.7" & = "3.19.1"} + "angstrom" {= "0.16.0"} + "base" + "fix" + "ppx_inline_test" {with-test} + "ppx_expect" + "ppx_deriving" + "bisect_ppx" + "odoc" {with-doc} + "ocamlformat" {build & = "0.26.2"} +] +build: [ + ["dune" "subst"] {dev} + [ + "dune" + "build" + "-p" + name + "-j" + jobs + "@install" + "@runtest" {with-test} + "@doc" {with-doc} + ] +] +pin-depends: [ + ["ppx_deriving_qcheck.0.6" "git+https://github.com/c-cube/qcheck.git#42429bf06ba12373cad02b1404f50d0ad6238af5"] +] +# Don't edit '*.opam' file manually. Use 'dune b @install' diff --git a/Lazarev/Lazarev.opam.template b/Lazarev/Lazarev.opam.template new file mode 100644 index 00000000..480da691 --- /dev/null +++ b/Lazarev/Lazarev.opam.template @@ -0,0 +1,4 @@ +pin-depends: [ + ["ppx_deriving_qcheck.0.6" "git+https://github.com/c-cube/qcheck.git#42429bf06ba12373cad02b1404f50d0ad6238af5"] +] +# Don't edit '*.opam' file manually. Use 'dune b @install' diff --git a/Lazarev/Makefile b/Lazarev/Makefile new file mode 100644 index 00000000..e234db4b --- /dev/null +++ b/Lazarev/Makefile @@ -0,0 +1,49 @@ +.PHONY: repl tests test fmt lint celan + +all: + dune build + +repl: + dune build ./REPL.exe && rlwrap _build/default/REPL.exe + +tests: test +test: + dune runtest + +celan: clean +clean: + @$(RM) -r _build _coverage + +fmt: + dune build @fmt --auto-promote + +lint: + dune build @lint --force + +release: + dune build --profile=release + dune runtest --profile=release + +install: + dune b @install --profile=release + dune install + +ODIG_SWITCHES = --odoc-theme=odig.gruvbox.light +ODIG_SWITCHES += --no-tag-index +ODIG_SWITCHES += --no-pkg-deps +odig: + odig odoc $(ODIG_SWITCHES) Lambda + +TEST_COV_D = /tmp/cov +COVERAGE_OPTS = --coverage-path $(TEST_COV_D) --expect lib/ --expect tests/ + +.PHONY: test_coverage coverage +test_coverage: coverage +coverage: + $(RM) -r $(TEST_COV_D) + mkdir -p $(TEST_COV_D) + BISECT_FILE=$(TEST_COV_D)/language dune runtest --no-print-directory \ + --instrument-with bisect_ppx --force + bisect-ppx-report html $(COVERAGE_OPTS) + bisect-ppx-report summary $(COVERAGE_OPTS) + @echo "Use 'xdg-open _coverage/index.html' to see coverage report" diff --git a/Lazarev/dune b/Lazarev/dune new file mode 100644 index 00000000..98e54536 --- /dev/null +++ b/Lazarev/dune @@ -0,0 +1,7 @@ +(env + (dev + (flags + (:standard -alert @deprecated -warn-error -A -w -3-9-32-34-58))) + (release + (flags + (:standard -alert @deprecated -warn-error +A -w +A-4-40-42-44-70)))) diff --git a/Lazarev/dune-project b/Lazarev/dune-project new file mode 100644 index 00000000..1615f112 --- /dev/null +++ b/Lazarev/dune-project @@ -0,0 +1,39 @@ +(lang dune 3.7) + +(generate_opam_files true) + +(cram enable) + +(license "LGPL-3.0-or-later WITH OCaml-LGPL-linking-exception") + +(authors "Andrey Lazarev ") + +(maintainers "Andrey Lazarev ") + +(bug_reports "https://github.com/Kakadu/fp25") + +(homepage "https://github.com/Kakadu/fp25") + +(package + (name Lazarev) + (synopsis "Interpreter") + (description "An interpreter for ML-like language") + (documentation "https://kakadu.github.io/fp25/docs/Lambda") + (version 0.1) + (depends + (dune + (= "3.19.1")) + (angstrom + (= "0.16.0")) + base + fix + (ppx_inline_test :with-test) + ppx_expect + ppx_deriving + bisect_ppx + (odoc :with-doc) + (ocamlformat + (and + :build + (= "0.26.2"))) + )) From af59cdadcb12ba13225e05989fde188899e42672 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Thu, 26 Mar 2026 04:19:41 +0300 Subject: [PATCH 02/28] Updated project info --- Lazarev/Lazarev.opam | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lazarev/Lazarev.opam b/Lazarev/Lazarev.opam index 80fcc513..4f06b164 100644 --- a/Lazarev/Lazarev.opam +++ b/Lazarev/Lazarev.opam @@ -1,8 +1,8 @@ # This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.1" -synopsis: "An interpreter for ML-like language" -description: "TODO" +synopsis: "Interpreter" +description: "An interpreter for ML-like language" maintainer: ["Andrey Lazarev "] authors: ["Andrey Lazarev "] license: "LGPL-3.0-or-later WITH OCaml-LGPL-linking-exception" From 6d486aedaba6dc7d13ea7ba529b9f17d58cf8c47 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Thu, 26 Mar 2026 04:21:43 +0300 Subject: [PATCH 03/28] Revert "Updated project info" This reverts commit af59cdadcb12ba13225e05989fde188899e42672. --- Lazarev/Lazarev.opam | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lazarev/Lazarev.opam b/Lazarev/Lazarev.opam index 4f06b164..80fcc513 100644 --- a/Lazarev/Lazarev.opam +++ b/Lazarev/Lazarev.opam @@ -1,8 +1,8 @@ # This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.1" -synopsis: "Interpreter" -description: "An interpreter for ML-like language" +synopsis: "An interpreter for ML-like language" +description: "TODO" maintainer: ["Andrey Lazarev "] authors: ["Andrey Lazarev "] license: "LGPL-3.0-or-later WITH OCaml-LGPL-linking-exception" From cb9638ee0fea6ac551268d7d53f9a83d19072fc3 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Thu, 26 Mar 2026 04:23:02 +0300 Subject: [PATCH 04/28] Updated project info Signed-off-by: Andrew Lazarev --- Lazarev/Lazarev.opam | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lazarev/Lazarev.opam b/Lazarev/Lazarev.opam index 80fcc513..4f06b164 100644 --- a/Lazarev/Lazarev.opam +++ b/Lazarev/Lazarev.opam @@ -1,8 +1,8 @@ # This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.1" -synopsis: "An interpreter for ML-like language" -description: "TODO" +synopsis: "Interpreter" +description: "An interpreter for ML-like language" maintainer: ["Andrey Lazarev "] authors: ["Andrey Lazarev "] license: "LGPL-3.0-or-later WITH OCaml-LGPL-linking-exception" From 0ffac301ac1435e873f6326c05ccef800c544351 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 28 Mar 2026 01:43:01 +0300 Subject: [PATCH 05/28] AST & Parsing done Signed-off-by: Andrew Lazarev --- Lazarev/lib/ast.ml | 165 +++++++++++++++++++ Lazarev/lib/ast.mli | 59 +++++++ Lazarev/lib/dune | 9 ++ Lazarev/lib/parser.ml | 284 +++++++++++++++++++++++++++++++++ Lazarev/lib/parser.mli | 27 ++++ Lazarev/lib/utils.mli | 48 ++++++ Lazarev/tests/ast_tests.ml | 110 +++++++++++++ Lazarev/tests/ast_tests.mli | 9 ++ Lazarev/tests/dune | 13 ++ Lazarev/tests/interpreter.t | 10 ++ Lazarev/tests/parser_tests.ml | 277 ++++++++++++++++++++++++++++++++ Lazarev/tests/parser_tests.mli | 9 ++ 12 files changed, 1020 insertions(+) create mode 100644 Lazarev/lib/ast.ml create mode 100644 Lazarev/lib/ast.mli create mode 100644 Lazarev/lib/dune create mode 100644 Lazarev/lib/parser.ml create mode 100644 Lazarev/lib/parser.mli create mode 100644 Lazarev/lib/utils.mli create mode 100644 Lazarev/tests/ast_tests.ml create mode 100644 Lazarev/tests/ast_tests.mli create mode 100644 Lazarev/tests/dune create mode 100644 Lazarev/tests/interpreter.t create mode 100644 Lazarev/tests/parser_tests.ml create mode 100644 Lazarev/tests/parser_tests.mli diff --git a/Lazarev/lib/ast.ml b/Lazarev/lib/ast.ml new file mode 100644 index 00000000..1373db5b --- /dev/null +++ b/Lazarev/lib/ast.ml @@ -0,0 +1,165 @@ +[@@@ocaml.text "*/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "*/*"] + +type name = + | Wildcard + | Real of string + +type unary_operation = + | Neg + | Not +[@@deriving show { with_path = false }] + +type binary_operation = + | Add + | Sub + | Mul + | Div + | Mod + | And + | Or + | Equal + | NotEqual + | Less + | LessEqual + | Greater + | GreaterEqual +[@@deriving show { with_path = false }] + +type let_mnemonic = + | Let + | LetRec +[@@deriving show { with_path = false }] + +type t = + | Unit + | Int of int + | Bool of bool + | Var of name + | Tuple of t * t * t list + | UnaryOp of unary_operation * t + | BinaryOp of binary_operation * t * t + | IfThenElse of t * t * t + | LetStatement of let_mnemonic * name * t + | LetExpr of let_mnemonic * name * t * t + | Abstraction of name * t + | Application of t * t + +let show_name = function + | Wildcard -> "_" + | Real name -> name +;; + +let rec show_ast = function + | Unit -> "unit" + | Int value -> string_of_int value + | Bool value -> string_of_bool value + | Var name -> show_name name + | Tuple (first, second, rest) -> + Format.sprintf + "Tuple(%s)" + (String.concat ", " (List.map show_ast (first :: second :: rest))) + | UnaryOp (op, expr) -> + Format.sprintf "%s(%s)" (show_unary_operation op) (show_ast expr) + | BinaryOp (op, left, right) -> + Format.sprintf + "%s(%s, %s)" + (show_binary_operation op) + (show_ast left) + (show_ast right) + | IfThenElse (cond, then_expr, else_expr) -> + Format.sprintf + "IfThenElse(%s, %s, %s)" + (show_ast cond) + (show_ast then_expr) + (show_ast else_expr) + | LetStatement (rf, name, statement) -> + Format.sprintf + "%s(%s, %s)" + (show_let_mnemonic rf) + (show_name name) + (show_ast statement) + | LetExpr (rf, name, lhs, rhs) -> + Format.sprintf + "%s(%s, %s, %s)" + (show_let_mnemonic rf) + (show_name name) + (show_ast lhs) + (show_ast rhs) + | Abstraction (name, expr) -> + Format.sprintf "Abs(%s, %s)" (show_name name) (show_ast expr) + | Application (lhs, rhs) -> Format.sprintf "App(%s, %s)" (show_ast lhs) (show_ast rhs) +;; + +let show_pretty_unary_operation = function + | Neg -> "-" + | Not -> "!" +;; + +let show_pretty_binary_operation = function + | Add -> "+" + | Sub -> "-" + | Mul -> "*" + | Div -> "/" + | Mod -> "mod" + | And -> "&&" + | Or -> "||" + | Equal -> "=" + | NotEqual -> "<>" + | Less -> "<" + | LessEqual -> "<=" + | Greater -> ">" + | GreaterEqual -> ">=" +;; + +let show_pretty_rec_flag = function + | Let -> "let" + | LetRec -> "let rec" +;; + +let rec show_pretty_ast = function + | Unit -> "()" + | Int value -> string_of_int value + | Bool value -> string_of_bool value + | Var name -> show_name name + | Tuple (first, second, rest) -> + Format.sprintf + "(%s)" + (String.concat ", " (List.map show_pretty_ast (first :: second :: rest))) + | UnaryOp (op, expr) -> + Format.sprintf "%s(%s)" (show_pretty_unary_operation op) (show_pretty_ast expr) + | BinaryOp (op, left, right) -> + Format.sprintf + "(%s %s %s)" + (show_pretty_ast left) + (show_pretty_binary_operation op) + (show_pretty_ast right) + | IfThenElse (cond, then_expr, else_expr) -> + Format.sprintf + "if (%s) then (%s) else (%s)" + (show_pretty_ast cond) + (show_pretty_ast then_expr) + (show_pretty_ast else_expr) + | LetStatement (rf, name, statement) -> + Format.sprintf + "%s %s = (%s)" + (show_pretty_rec_flag rf) + (show_name name) + (show_pretty_ast statement) + | LetExpr (rf, name, lhs, rhs) -> + Format.sprintf + "%s %s = (%s) in (%s)" + (show_pretty_rec_flag rf) + (show_name name) + (show_pretty_ast lhs) + (show_pretty_ast rhs) + | Abstraction (var, expr) -> + Format.sprintf "fun %s -> %s" (show_name var) (show_pretty_ast expr) + | Application (lhs, rhs) -> + Format.sprintf "((%s) (%s))" (show_pretty_ast lhs) (show_pretty_ast rhs) +;; diff --git a/Lazarev/lib/ast.mli b/Lazarev/lib/ast.mli new file mode 100644 index 00000000..07b8059b --- /dev/null +++ b/Lazarev/lib/ast.mli @@ -0,0 +1,59 @@ +[@@@ocaml.text "/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "/*"] + +(** Type for name of variable, used in variable, abstraction, let, letrec *) +type name = + | Wildcard (** Wildcard name [_] *) + | Real of string (** Real name (any string) *) + +(** Type for any unary operation in language *) +type unary_operation = + | Neg (** Integer negation [-x] *) + | Not (** Logical inversion [!x] *) + +(** Type for any binary operation in language *) +type binary_operation = + | Add (** Addition [a + b] *) + | Sub (** Subtraction [a - b] *) + | Mul (** Multiplication [a * b] *) + | Div (** Division [a / b] *) + | Mod (** Remainder [a mod b] *) + | And (** [a && b] *) + | Or (** [a || b] *) + | Equal (** Comparing on equal [a = b] *) + | NotEqual (** Comparing on not eqaul [a <> b] *) + | Less (** Compare on less [a < b] *) + | LessEqual (** Compare on less or equal [a <= b] *) + | Greater (** Compare on greater [a > b] *) + | GreaterEqual (** Compare on greater or equal [a >= b] *) + +(** Type for indicating recursive let expression *) +type let_mnemonic = + | Let (** Common [let] *) + | LetRec (** Recursive [let rec] *) + +(** Type for abstract-syntax tree node *) +type t = + | Unit (** Unit literal *) + | Int of int (** Integer literal [42] *) + | Bool of bool (** Boolean literal [true] *) + | Var of name (** Variable [x] *) + | Tuple of t * t * t list (** Tuple [(x, y, ..., z)] *) + | UnaryOp of unary_operation * t (** Unary operation [..y] *) + | BinaryOp of binary_operation * t * t (** Binary operation [x .. y] *) + | IfThenElse of t * t * t (** If-then-else expression [if ... then ... else ...] *) + | LetStatement of let_mnemonic * name * t (** Let statement [let x = ...] *) + | LetExpr of let_mnemonic * name * t * t (** Let expression [let x = ... in ...] *) + | Abstraction of name * t (** Lambda abstraction [fun x -> ...] *) + | Application of t * t (** Application [(f x)] *) + +(** Shows AST in verbose format *) +val show_ast : t -> string + +(** Shows AST in human readable format *) +val show_pretty_ast : t -> string diff --git a/Lazarev/lib/dune b/Lazarev/lib/dune new file mode 100644 index 00000000..ab70d240 --- /dev/null +++ b/Lazarev/lib/dune @@ -0,0 +1,9 @@ +(library + (name mini_ml_lib) + (public_name Lazarev.MiniML) + (modules Ast Parser Utils) + (modules_without_implementation utils) + (preprocess + (pps ppx_deriving.show)) + (instrumentation + (backend bisect_ppx))) diff --git a/Lazarev/lib/parser.ml b/Lazarev/lib/parser.ml new file mode 100644 index 00000000..8102c18d --- /dev/null +++ b/Lazarev/lib/parser.ml @@ -0,0 +1,284 @@ +[@@@ocaml.text "*/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "*/*"] + +type error = + | UnexpectedEnd + | UnexpectedRest of string + | SyntaxError of string + +type 'a result = + | Parsed of 'a * char list + | ParseError of error + +let return res chars = Parsed (res, chars) +let fail error _ = ParseError error + +let fix = + let rec fix f s = f (fix f) s in + fix +;; + +let bind parser transform chars = + match parser chars with + | Parsed (a, rest) -> transform a rest + | ParseError _ as e -> e +;; + +let ( >>= ) = bind +let ( let* ) = bind +let string_of_chars chars = chars |> List.to_seq |> String.of_seq +let chars_of_string string = string |> String.to_seq |> List.of_seq + +let satisfy predicate chars = + match chars with + | h :: tl when predicate h -> return h tl + | h :: tl -> fail (SyntaxError (string_of_chars (h :: tl))) tl + | [] -> fail UnexpectedEnd [] +;; + +let char c = satisfy (( = ) c) + +let ( <*> ) parser_func parser chars = + match parser_func chars with + | ParseError _ as e -> e + | Parsed (f, tail) -> + (match parser tail with + | ParseError _ as e -> e + | Parsed (a, tl) -> return (f a) tl) +;; + +let ( <|> ) left right chars = + match left chars with + | ParseError _ -> right chars + | Parsed _ as res -> res +;; + +let ( >>| ) parser transform chars = + match parser chars with + | ParseError _ as e -> e + | Parsed (x, tl) -> return (transform x) tl +;; + +let choice parsers = List.fold_left ( <|> ) (fail UnexpectedEnd) parsers +let ( *> ) left right = left >>= fun _ -> right +let ( <* ) left right = left >>= fun a -> right >>= fun _ -> return a + +let rec zero_many parser chars = + match parser chars with + | ParseError _ -> return [] chars + | Parsed (a, rest) -> + (let* a_tail = zero_many parser in + return (a :: a_tail)) + rest +;; + +let one_many parser = + let* x = parser in + let* xs = zero_many parser in + return (x :: xs) +;; + +let alpha = + satisfy (function + | 'a' .. 'z' -> true + | 'A' .. 'Z' -> true + | _ -> false) +;; + +let digit = + satisfy (function + | '0' .. '9' -> true + | _ -> false) +;; + +let chars string = + match chars_of_string string with + | [] -> fail UnexpectedEnd + | c :: rest -> List.fold_left ( *> ) (char c) (List.map char rest) +;; + +let reserved str = + match str with + | "let" -> true + | "rec" -> true + | "in" -> true + | "if" -> true + | "then" -> true + | "else" -> true + | "fun" -> true + | "false" -> true + | "true" -> true + | "mod" -> true + | _ -> false +;; + +let ws0 = zero_many (char ' ' <|> char '\t' <|> char '\n') +let ws1 = one_many (char ' ' <|> char '\t' <|> char '\n') +let parens parser = ws0 *> char '(' *> parser <* ws0 <* char ')' + +let identifier = + let wildcard = + let* _ = char '_' in + return Ast.Wildcard + in + let real = + let* x = alpha in + let* xs = zero_many (alpha <|> digit) in + let name = string_of_chars (x :: xs) in + if reserved name then fail (SyntaxError name) else return (Ast.Real name) + in + wildcard <|> real +;; + +let term = + let integer = + let* chars = one_many digit in + return (Ast.Int (int_of_string (string_of_chars chars))) + in + let boolean = + let parser_true = chars "false" >>| fun _ -> Ast.Bool false in + let parser_false = chars "true" >>| fun _ -> Ast.Bool true in + parser_true <|> parser_false + in + let variable = + let* name = identifier in + return (Ast.Var name) + in + let unit = + let* _ = chars "()" in + return Ast.Unit + in + integer <|> boolean <|> variable <|> unit +;; + +let arguments parser = one_many (ws1 *> parser) + +let apply_precedence parser operators = + let length = Array.length operators in + let rec helper level = + if level >= length + then parser + else ( + let xs = operators.(level) in + return (List.fold_left (fun acc (op, r) -> op acc r)) + <*> helper (level + 1) + <*> zero_many + (choice + (List.map + (fun (sign, left) -> + let* right = ws0 *> sign *> ws0 *> helper (level + 1) in + return (left, right)) + xs))) + in + helper 0 +;; + +let atom = + let binary typ left right = Ast.BinaryOp (typ, left, right) in + let unary operation typ parser = + let* _ = chars operation in + let* expr = parser in + return (Ast.UnaryOp (typ, expr)) + in + let neg = unary "-" Ast.Neg in + let not = unary "!" Ast.Not in + let tuple parser = + let* _ = char '(' in + let* fst = parser in + let* rest = one_many (ws0 *> char ',' *> ws0 *> parser) in + let* _ = char ')' in + return (Ast.Tuple (fst, List.hd rest, List.tl rest)) + in + let application parser1 parser2 = + let* _ = char '(' in + let* name = parser1 in + let* args = arguments parser2 in + let* _ = char ')' in + return (List.fold_left (fun left right -> Ast.Application (left, right)) name args) + in + let abstraction parser = + let* _ = chars "fun" in + let* args = arguments identifier in + let* _ = ws0 *> chars "->" in + let* expr = ws0 *> parser in + return (List.fold_right (fun left right -> Ast.Abstraction (left, right)) args expr) + in + let if_expr parser1 parser2 = + let* _ = chars "if" in + let* cond = ws1 *> parser1 in + let* _ = ws1 *> chars "then" in + let* on_true = ws1 *> parser2 in + let* _ = ws1 *> chars "else" in + let* on_false = ws1 *> parser2 in + return (Ast.IfThenElse (cond, on_true, on_false)) + in + let letrec mnemo rec_flag parser1 parser2 = + let* _ = chars mnemo in + let* name = ws1 *> identifier in + let* _ = ws0 *> char '=' in + let* expr1 = ws0 *> parser1 in + let* _ = ws1 *> chars "in" in + let* expr2 = ws1 *> parser2 in + return (Ast.LetExpr (rec_flag, name, expr1, expr2)) + in + let let_expr = letrec "let" Ast.Let in + let let_rec_expr = letrec "let rec" Ast.LetRec in + fix (fun atom -> + let atom_fix = + fix (fun inner -> + term + <|> choice [ neg inner; not inner ] + <|> application atom inner + <|> abstraction inner + <|> tuple inner + <|> if_expr atom inner + <|> let_expr atom inner + <|> let_rec_expr atom inner + <|> parens atom) + in + apply_precedence + atom_fix + [| [ chars "&&", binary Ast.And ] + ; [ chars "||", binary Ast.Or ] + ; [ char '=', binary Ast.Equal + ; chars "<>", binary Ast.NotEqual + ; char '<', binary Ast.Less + ; chars "<=", binary Ast.LessEqual + ; char '>', binary Ast.Greater + ; chars ">=", binary Ast.GreaterEqual + ] + ; [ char '+', binary Ast.Add; char '-', binary Ast.Sub ] + ; [ chars "mod", binary Ast.Mod + ; char '*', binary Ast.Mul + ; char '/', binary Ast.Div + ] + ; [ (chars "@@", fun left right -> Ast.Application (left, right)) ] + |]) +;; + +let wrap_result = function + | Parsed (a, rest) when rest = [] -> Parsed (a, rest) + | Parsed (_, rest) -> ParseError (UnexpectedRest (string_of_chars rest)) + | ParseError _ as e -> e +;; + +let parse_one string = + let atom = ws0 *> atom <* ws0 in + chars_of_string string |> atom |> wrap_result +;; + +let show_error = function + | UnexpectedEnd -> "Unexpected end of input" + | UnexpectedRest s -> Format.sprintf {|Unparsed symbols: "%s"|} s + | SyntaxError s -> Format.sprintf {|Syntax error: "%s"|} s +;; + +let show_result = function + | Parsed (ast, _) -> Ast.show_ast ast + | ParseError e -> show_error e +;; diff --git a/Lazarev/lib/parser.mli b/Lazarev/lib/parser.mli new file mode 100644 index 00000000..17e211f8 --- /dev/null +++ b/Lazarev/lib/parser.mli @@ -0,0 +1,27 @@ +[@@@ocaml.text "*/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "*/*"] + +(** Type for parsing error *) +type error = + | UnexpectedEnd (** When end of source unexpectedly reached *) + | UnexpectedRest of string (** When not all characters where parsed *) + | SyntaxError of string (** For other errors *) + +(** Type for result of parsing *) +type 'a result = + | Parsed of 'a * char list + | ParseError of error + +(** Shows error in human readable format *) +val show_error : error -> string + +(** Shows result in human readable format *) +val show_result : Ast.t result -> string + +(** Parse expression *) +val parse_one : string -> Ast.t result diff --git a/Lazarev/lib/utils.mli b/Lazarev/lib/utils.mli new file mode 100644 index 00000000..0b0e9bfa --- /dev/null +++ b/Lazarev/lib/utils.mli @@ -0,0 +1,48 @@ +[@@@ocaml.text "*/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "*/*"] + +module type MONAD = sig + type 'a t + + val return : 'a -> 'a t + val bind : 'a t -> ('a -> 'b t) -> 'b t +end + +module type MONAD_ERROR = sig + type ('e, 'a) t + + val return : 'a -> ('e, 'a) t + val bind : ('e, 'a) t -> ('a -> ('e, 'b) t) -> ('e, 'b) t + val fail : 'e -> ('e, 'a) t + val catch : ('e, 'a) t -> ('e -> ('e, 'a) t) -> ('e, 'a) t +end + +module type READER_MONAD = sig + type ('s, 'a) t + + val return : 'a -> ('s, 'a) t + val bind : ('s, 'a) t -> ('a -> ('s, 'b) t) -> ('s, 'b) t + val read : ('s, 's) t + val run : ('s, 'a) t -> 's -> 'a +end + +module type WRITER_MONAD = sig + type ('s, 'a) t + + val return : 'a -> ('s, 'a) t + val bind : ('s, 'a) t -> ('a -> ('s, 'b) t) -> ('s, 'b) t + val write : 's -> ('s, unit) t + val run : ('s, 'a) t -> 's list * 'a +end + +module type STATE_MONAD = sig + include READER_MONAD + include WRITER_MONAD with type ('s, 'a) t := ('s, 'a) t + + val run : ('st, 'a) t -> 'st -> 'st * 'a +end diff --git a/Lazarev/tests/ast_tests.ml b/Lazarev/tests/ast_tests.ml new file mode 100644 index 00000000..8cbbf45d --- /dev/null +++ b/Lazarev/tests/ast_tests.ml @@ -0,0 +1,110 @@ +[@@@ocaml.text "/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "/*"] + +module Ast = Mini_ml_lib.Ast + +let wildcard = Ast.Wildcard +let name name = Ast.Real name +let var name = Ast.Var (Ast.Real name) +let const value = Ast.Int value +let bool value = Ast.Bool value +let neg expr = Ast.UnaryOp (Ast.Neg, expr) +let not expr = Ast.UnaryOp (Ast.Not, expr) +let add lhs rhs = Ast.BinaryOp (Ast.Add, lhs, rhs) +let sub lhs rhs = Ast.BinaryOp (Ast.Sub, lhs, rhs) +let mul lhs rhs = Ast.BinaryOp (Ast.Mul, lhs, rhs) +let div lhs rhs = Ast.BinaryOp (Ast.Div, lhs, rhs) +let rem lhs rhs = Ast.BinaryOp (Ast.Mod, lhs, rhs) + +let expect ast verbose pretty = + Ast.show_ast ast = verbose && Ast.show_pretty_ast ast = pretty +;; + +let%test "Unit" = expect Ast.Unit "unit" "()" +let%test "Variable" = expect (var "someVariable") "someVariable" "someVariable" + +let%test "Arithmetic 1" = + expect + (add (add (const 123) (const 456)) (const 789)) + "Add(Add(123, 456), 789)" + "((123 + 456) + 789)" +;; + +let%test "Arithmetic 2" = + expect + (neg (mul (const 2) (div (var "y") (var "x")))) + "Neg(Mul(2, Div(y, x)))" + "-((2 * (y / x)))" +;; + +let%test "Arithmetic 3" = + expect + (rem (const 44) (sub (var "y") (const 1))) + "Mod(44, Sub(y, 1))" + "(44 mod (y - 1))" +;; + +let eq lhs rhs = Ast.BinaryOp (Ast.Equal, lhs, rhs) +let ne lhs rhs = Ast.BinaryOp (Ast.NotEqual, lhs, rhs) +let lt lhs rhs = Ast.BinaryOp (Ast.Less, lhs, rhs) +let le lhs rhs = Ast.BinaryOp (Ast.LessEqual, lhs, rhs) +let gt lhs rhs = Ast.BinaryOp (Ast.Greater, lhs, rhs) +let ge lhs rhs = Ast.BinaryOp (Ast.GreaterEqual, lhs, rhs) +let ast_and lhs rhs = Ast.BinaryOp (Ast.And, lhs, rhs) +let ast_or lhs rhs = Ast.BinaryOp (Ast.Or, lhs, rhs) + +let%test "Bool 1" = + expect (ast_or (bool true) (bool false)) "Or(true, false)" "(true || false)" +;; + +let%test "Bool 2" = + expect + (not (eq (le (var "a0") (var "a1")) (var "b"))) + "Not(Equal(LessEqual(a0, a1), b))" + "!(((a0 <= a1) = b))" +;; + +let%test "Bool 3" = + expect + (gt (const 42) (ne (var "flag") (bool false))) + "Greater(42, NotEqual(flag, false))" + "(42 > (flag <> false))" +;; + +let%test "Bool 4" = + expect + (ast_and (ast_or (lt (const 12) (const 24)) (var "x")) (ge (var "y") (var "z"))) + "And(Or(Less(12, 24), x), GreaterEqual(y, z))" + "(((12 < 24) || x) && (y >= z))" +;; + +let app func arg = Ast.Application (func, arg) +let abs arg expr = Ast.Abstraction (arg, expr) + +let%test "Applications & abstractions" = + expect + (app (app (abs wildcard (abs (name "a") (const 12))) (var "x1")) (var "x2")) + "App(App(Abs(_, Abs(a, 12)), x1), x2)" + "((((fun _ -> fun a -> 12) (x1))) (x2))" +;; + +let let_st name expr = Ast.LetStatement (Ast.Let, name, expr) +let letrec_st name expr = Ast.LetStatement (Ast.LetRec, name, expr) + +let%test "Let 1" = + expect (let_st (name "value") (var "value")) "Let(value, value)" "let value = (value)" +;; + +let%test "Let 2" = + expect + (letrec_st + (name "fact") + (abs (name "n") (app (var "fact") (sub (var "n") (const 1))))) + "LetRec(fact, Abs(n, App(fact, Sub(n, 1))))" + "let rec fact = (fun n -> ((fact) ((n - 1))))" +;; diff --git a/Lazarev/tests/ast_tests.mli b/Lazarev/tests/ast_tests.mli new file mode 100644 index 00000000..639d1975 --- /dev/null +++ b/Lazarev/tests/ast_tests.mli @@ -0,0 +1,9 @@ +[@@@ocaml.text "/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "/*"] + +(* This file is intentionally empty *) diff --git a/Lazarev/tests/dune b/Lazarev/tests/dune new file mode 100644 index 00000000..4c56f1cf --- /dev/null +++ b/Lazarev/tests/dune @@ -0,0 +1,13 @@ +(library + (name tests) + (modules ast_tests parser_tests) + (libraries mini_ml_lib qcheck) + (inline_tests) + (preprocess + (pps ppx_expect ppx_deriving.show)) + (instrumentation + (backend bisect_ppx))) + +(cram + (applies_to interpreter) + (deps ../bin/REPL.exe)) diff --git a/Lazarev/tests/interpreter.t b/Lazarev/tests/interpreter.t new file mode 100644 index 00000000..2ebc0bdd --- /dev/null +++ b/Lazarev/tests/interpreter.t @@ -0,0 +1,10 @@ +Copyright 2021-2024, Kakadu and contributors +SPDX-License-Identifier: CC0-1.0 + +Cram tests here. They run and compare program output to the expected output +https://dune.readthedocs.io/en/stable/tests.html#cram-tests +Use `dune promote` after you change things that should runned + +If you need to put sample program and use it both in your interpreter and preinstalled one, +you could put it into separate file. Thise will need stanza `(cram (deps demo_input.txt))` +in the dune file diff --git a/Lazarev/tests/parser_tests.ml b/Lazarev/tests/parser_tests.ml new file mode 100644 index 00000000..9dba624c --- /dev/null +++ b/Lazarev/tests/parser_tests.ml @@ -0,0 +1,277 @@ +[@@@ocaml.text "/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "/*"] + +open QCheck +module Parser = Mini_ml_lib.Parser +module Ast = Mini_ml_lib.Ast + +let parse_and_print input = + (match Parser.parse_one input with + | Parsed (a, _) -> Ast.show_ast a + | ParseError e -> Parser.show_error e) + |> print_endline +;; + +(* Test if valid expressions are parsed *) + +let%expect_test "Correct parsing" = + " (((45 \t + x) + \t ((213)))) " |> parse_and_print; + [%expect "Add(Add(45, x), 213)"]; + "\n x \t\n - \t\n 5 \t\n" |> parse_and_print; + [%expect "Sub(x, 5)"]; + "x001 + x002 - x003 + x004 + complexVariable222 - simpleVariable333" |> parse_and_print; + [%expect + "Sub(Add(Add(Sub(Add(x001, x002), x003), x004), complexVariable222), \ + simpleVariable333)"]; + "(false) && (true) \t = \t (1) > (3)" |> parse_and_print; + [%expect "And(false, Greater(Equal(true, 1), 3))"]; + "(4) mod (5 / 2)" |> parse_and_print; + [%expect "Mod(4, Div(5, 2))"]; + "(2 + 2) * 2 <> 2 + 2 * 2" |> parse_and_print; + [%expect "NotEqual(Mul(Add(2, 2), 2), Add(2, Mul(2, 2)))"]; + "(1, 2, 3, (false, true), (1 - 2))" |> parse_and_print; + [%expect "Tuple(1, 2, 3, Tuple(false, true), Sub(1, 2))"]; + "fun x->fun y->fun z->(x + y + z)" |> parse_and_print; + [%expect "Abs(x, Abs(y, Abs(z, Add(Add(x, y), z))))"]; + "(fun x -> (2 * x + 1), fun x -> (x / 2 - 1))" |> parse_and_print; + [%expect "Tuple(Abs(x, Add(Mul(2, x), 1)), Abs(x, Sub(Div(x, 2), 1)))"]; + "if (var > 0) then var else -var" |> parse_and_print; + [%expect "IfThenElse(Greater(var, 0), var, Neg(var))"]; + "if var1 then 1 else \n if var2 then 2 else \n if var3 then 3 else 4" |> parse_and_print; + [%expect "IfThenElse(var1, 1, IfThenElse(var2, 2, IfThenElse(var3, 3, 4)))"]; + "if a then 1 else 2 + if b then true else false" |> parse_and_print; + [%expect "Add(IfThenElse(a, 1, 2), IfThenElse(b, true, false))"]; + "fun a -> -(if a then 1 else 2)" |> parse_and_print; + [%expect "Abs(a, Neg(IfThenElse(a, 1, 2)))"]; + "let a = 1 in let b = 2 in let c = 3 in (a + b + c)" |> parse_and_print; + [%expect "Let(a, 1, Let(b, 2, Let(c, 3, Add(Add(a, b), c))))"] +;; + +(* Test if invalid expressions are not parsed *) + +let%expect_test "Invalid expressions" = + "( )" |> parse_and_print; + [%expect {|Syntax error: ")"|}]; + "(1 $ 2" |> parse_and_print; + [%expect {|Syntax error: "$ 2"|}]; + "var & mask)" |> parse_and_print; + [%expect {|Unparsed symbols: "& mask)"|}]; + "var += 1" |> parse_and_print; + [%expect {|Unparsed symbols: "+= 1"|}]; + "(567 / 3) + (567 % 3" |> parse_and_print; + [%expect {|Unparsed symbols: "+ (567 % 3"|}]; + "(call 1invalid2identifier)" |> parse_and_print; + [%expect {|Syntax error: "1invalid2identifier)"|}]; + "+ 1 2 3" |> parse_and_print; + [%expect {|Syntax error: "+ 1 2 3"|}]; + "(1, 2, 3 helloWorld)" |> parse_and_print; + [%expect {|Syntax error: ", 2, 3 helloWorld)"|}]; + "fun x y ->" |> parse_and_print; + [%expect {|Syntax error: "fun x y ->"|}]; + "if a <> 0 then 1" |> parse_and_print; + [%expect {|Syntax error: "if a <> 0 then 1"|}]; + "let in = 1 in in" |> parse_and_print; + [%expect {|Syntax error: "let in = 1 in in"|}]; + "let mod = 1 in var0 + var1" |> parse_and_print; + [%expect {|Syntax error: "let mod = 1 in var0 + var1"|}]; + "let false = 1 in true" |> parse_and_print; + [%expect {|Syntax error: "let false = 1 in true"|}]; + "let true = 1 in false" |> parse_and_print; + [%expect {|Syntax error: "let true = 1 in false"|}]; + "(1, 2, (if, then))" |> parse_and_print; + [%expect {|Syntax error: ", 2, (if, then))"|}]; + "(then, 3)" |> parse_and_print; + [%expect {|Syntax error: "then, 3)"|}]; + "let var = 1" |> parse_and_print; + [%expect {|Syntax error: "let var = 1"|}] +;; + +let same lhs rhs = + match Parser.parse_one lhs with + | ParseError _ -> false + | Parsed (a, _) -> + (match Parser.parse_one rhs with + | ParseError _ -> false + | Parsed (b, _) -> a = b) +;; + +(* Test if syntax sugar for application & abstraction arguments works *) + +let%test "Abstraction syntax sugar" = + same "fun x -> (fun y -> (fun z -> (x + y + z)))" "fun x y z -> (x + y + z)" +;; + +let%test "Application syntax sugar" = + same "(((func arg0) (-arg1)) (!arg2))" "(func arg0 -arg1 !arg2)" +;; + +(* Test if apply operator works *) + +let%test "Application operator 1" = + same "(func arg0 arg1 arg2)" "func @@ arg0 @@ arg1 @@ arg2" +;; + +let%test "Application operator 2" = + same "(func (func1 arg1) arg)" "func @@ (func1 @@ arg1) @@ arg" +;; + +let%test "Application operator 3" = + same "((func arg) (func1 arg1))" "(func @@ arg) @@ (func1 @@ arg1)" +;; + +(* QCheck tests *) + +let gen_name = + let open Gen in + let capital_alpha = char_range 'A' 'Z' in + let alphanum = oneof [ char_range 'a' 'z'; char_range 'A' 'Z'; char_numeral ] in + let ident = + map + (fun chars -> chars |> List.to_seq |> String.of_seq) + (let* first = capital_alpha in + let* rest = list_size (int_range 1 10) alphanum in + return (first :: rest)) + in + map (fun s -> Ast.Real s) ident +;; + +let gen_unary_operation = Gen.oneof [ Gen.return Ast.Neg; Gen.return Ast.Not ] + +let gen_binary_operation = + Gen.oneof + (List.map + Gen.return + [ Ast.Add + ; Ast.Sub + ; Ast.Mul + ; Ast.Div + ; Ast.Mod + ; Ast.And + ; Ast.Or + ; Ast.Equal + ; Ast.NotEqual + ; Ast.Less + ; Ast.LessEqual + ; Ast.Greater + ; Ast.GreaterEqual + ]) +;; + +let gen_rec_flag = Gen.oneof_weighted [ 5, Gen.return Ast.Let; 1, Gen.return Ast.LetRec ] + +let gen_ast_depth = + let open Gen in + fix (fun gen size -> + if size <= 0 + then + oneof + [ return Ast.Unit + ; map (fun i -> Ast.Int i) (int_range 0 100000) + ; map (fun b -> Ast.Bool b) bool + ; map (fun n -> Ast.Var n) gen_name + ] + else ( + let sub = gen (size / 2) in + let sub_small = gen (size / 3) in + let sub_tiny = oneof [ gen 1; gen 2 ] in + oneof_weighted + [ 1, map (fun i -> Ast.Int i) (int_range 0 100000) + ; 1, map (fun b -> Ast.Bool b) bool + ; 1, map (fun n -> Ast.Var n) gen_name + ; 2, map2 (fun op expr -> Ast.UnaryOp (op, expr)) gen_unary_operation sub + ; ( 4 + , map3 + (fun op left right -> Ast.BinaryOp (op, left, right)) + gen_binary_operation + sub + sub ) + ; ( 2 + , Gen.map3 + (fun first second rest -> Ast.Tuple (first, second, rest)) + sub_tiny + sub_tiny + (list_size (int_range 0 5) sub_tiny) ) + ; 4, map2 (fun arg expr -> Ast.Abstraction (arg, expr)) gen_name sub + ; 4, map2 (fun func arg -> Ast.Application (func, arg)) sub_small sub + ; ( 2 + , map3 + (fun cond on_true on_false -> Ast.IfThenElse (cond, on_true, on_false)) + sub_small + sub + sub ) + ; ( 4 + , map4 + (fun rf name expr1 expr2 -> Ast.LetExpr (rf, name, expr1, expr2)) + gen_rec_flag + gen_name + sub_small + sub ) + ])) +;; + +let gen_ast limit = Gen.sized (fun size -> gen_ast_depth (min size limit)) +let gen_expr = Gen.map Ast.show_pretty_ast (gen_ast 5) + +let roundtrip_test_1 = + Test.make + ~name:"Parser round-trip 1" + ~count:50 + (make ~print:Ast.show_pretty_ast (gen_ast 7)) + (fun ast -> + let string = Ast.show_pretty_ast ast in + match Parser.parse_one string with + | Parsed (a, _) -> ast = a + | ParseError _ -> false) +;; + +let roundtrip_test_2 = + Test.make + ~name:"Parser round-trip 2" + ~count:50 + (make ~print:Fun.id gen_expr) + (fun expr -> + match Parser.parse_one expr with + | Parsed (a, _) -> expr = Ast.show_pretty_ast a + | ParseError _ -> false) +;; + +let parser_idempotent_test = + Test.make + ~name:"Parser idempotence" + ~count:20 + (make ~print:Fun.id gen_expr) + (fun expr -> + let ast1 = Parser.parse_one expr in + let ast2 = Parser.parse_one expr in + ast1 = ast2) +;; + +let printer_idempotent_test = + Test.make + ~name:"Printer idempotence" + ~count:20 + (make ~print:Ast.show_pretty_ast (gen_ast 10)) + (fun ast -> + let string1 = Ast.show_pretty_ast ast in + let string2 = Ast.show_pretty_ast ast in + string1 = string2) +;; + +let%test "QCheck test" = + let res = + QCheck_runner.run_tests + ~long:true + ~verbose:true + [ roundtrip_test_1 + ; roundtrip_test_2 + ; parser_idempotent_test + ; printer_idempotent_test + ] + in + res = 0 +;; diff --git a/Lazarev/tests/parser_tests.mli b/Lazarev/tests/parser_tests.mli new file mode 100644 index 00000000..639d1975 --- /dev/null +++ b/Lazarev/tests/parser_tests.mli @@ -0,0 +1,9 @@ +[@@@ocaml.text "/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "/*"] + +(* This file is intentionally empty *) From 07aa153ada02f6ae5cef7c7ec32b5c9ca0336d3e Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 28 Mar 2026 01:49:50 +0300 Subject: [PATCH 06/28] Add wildcard names to generator Signed-off-by: Andrew Lazarev --- Lazarev/tests/parser_tests.ml | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Lazarev/tests/parser_tests.ml b/Lazarev/tests/parser_tests.ml index 9dba624c..eebc5e84 100644 --- a/Lazarev/tests/parser_tests.ml +++ b/Lazarev/tests/parser_tests.ml @@ -126,7 +126,7 @@ let%test "Application operator 3" = (* QCheck tests *) -let gen_name = +let gen_real_name = let open Gen in let capital_alpha = char_range 'A' 'Z' in let alphanum = oneof [ char_range 'a' 'z'; char_range 'A' 'Z'; char_numeral ] in @@ -140,6 +140,12 @@ let gen_name = map (fun s -> Ast.Real s) ident ;; +let gen_any_name = + let open Gen in + let wildcard = return Ast.Wildcard in + oneof [ gen_real_name; wildcard ] +;; + let gen_unary_operation = Gen.oneof [ Gen.return Ast.Neg; Gen.return Ast.Not ] let gen_binary_operation = @@ -173,7 +179,7 @@ let gen_ast_depth = [ return Ast.Unit ; map (fun i -> Ast.Int i) (int_range 0 100000) ; map (fun b -> Ast.Bool b) bool - ; map (fun n -> Ast.Var n) gen_name + ; map (fun n -> Ast.Var n) gen_real_name ] else ( let sub = gen (size / 2) in @@ -182,7 +188,7 @@ let gen_ast_depth = oneof_weighted [ 1, map (fun i -> Ast.Int i) (int_range 0 100000) ; 1, map (fun b -> Ast.Bool b) bool - ; 1, map (fun n -> Ast.Var n) gen_name + ; 1, map (fun n -> Ast.Var n) gen_real_name ; 2, map2 (fun op expr -> Ast.UnaryOp (op, expr)) gen_unary_operation sub ; ( 4 , map3 @@ -196,7 +202,7 @@ let gen_ast_depth = sub_tiny sub_tiny (list_size (int_range 0 5) sub_tiny) ) - ; 4, map2 (fun arg expr -> Ast.Abstraction (arg, expr)) gen_name sub + ; 4, map2 (fun arg expr -> Ast.Abstraction (arg, expr)) gen_any_name sub ; 4, map2 (fun func arg -> Ast.Application (func, arg)) sub_small sub ; ( 2 , map3 @@ -208,7 +214,7 @@ let gen_ast_depth = , map4 (fun rf name expr1 expr2 -> Ast.LetExpr (rf, name, expr1, expr2)) gen_rec_flag - gen_name + gen_any_name sub_small sub ) ])) From 77bb3f59243860ecf88ab03e4da0c9011c074906 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 11 Apr 2026 00:34:24 +0300 Subject: [PATCH 07/28] Interpreter finished Signed-off-by: Andrew Lazarev --- Lazarev/lib/dune | 2 +- Lazarev/lib/interpreter.ml | 216 ++++++++++++++++++++++++++++++++++++ Lazarev/lib/interpreter.mli | 44 ++++++++ 3 files changed, 261 insertions(+), 1 deletion(-) create mode 100644 Lazarev/lib/interpreter.ml create mode 100644 Lazarev/lib/interpreter.mli diff --git a/Lazarev/lib/dune b/Lazarev/lib/dune index ab70d240..3cca3e00 100644 --- a/Lazarev/lib/dune +++ b/Lazarev/lib/dune @@ -1,7 +1,7 @@ (library (name mini_ml_lib) (public_name Lazarev.MiniML) - (modules Ast Parser Utils) + (modules Ast Interpreter Parser Utils) (modules_without_implementation utils) (preprocess (pps ppx_deriving.show)) diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml new file mode 100644 index 00000000..75699c10 --- /dev/null +++ b/Lazarev/lib/interpreter.ml @@ -0,0 +1,216 @@ +[@@@ocaml.text "/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "/*"] + +type error = + | ExhaustedSteps + | ZeroDivision + | InvalidApplication + | InvalidLet + | UnboundVariable of Ast.name + | TypeMismatch of string * string + +type 'a result = + | Eval of 'a + | EvalError of error + +type step_limit = + | Unlimited + | Limited of int + +type env = (Ast.name * value) list * step_limit +and variables = (Ast.name * value) list + +and value = + | Unit + | Int of int + | Bool of bool + | Tuple of value * value * value list + | Closure of Ast.t * env + | BuiltinAbstraction of (value -> value result) + +module State : Utils.STATE_MONAD = struct + type ('s, 'a) t = 's -> 's * 'a + + let return x st = st, x + + let bind x transform state = + let st, x = x state in + transform x st + ;; + + let read : ('st, 'st) t = fun state -> state, state + let write : 'st -> ('st, unit) t = fun s _ -> s, () + let run func state = func state +end + +let show_value_type = function + | Unit -> "unit" + | Int _ -> "int" + | Bool _ -> "bool" + | Tuple _ -> "" + | Closure _ -> "" + | BuiltinAbstraction _ -> "" +;; + +let show_value = function + | Unit -> "()" + | Int int -> string_of_int int + | Bool bool -> string_of_bool bool + | _ -> "" +;; + +module Eval (M : Utils.STATE_MONAD) = struct + let return x = M.return (Eval x) + let fail e = M.return (EvalError e) + + let bind x transform = + M.bind x (function + | Eval x -> transform x + | EvalError e -> M.return (EvalError e)) + ;; + + let get_vars = M.bind M.read (fun env -> M.return (fst env)) + let set_vars vars = M.bind M.read (fun env -> M.write (vars, snd env)) + let get_limit = M.bind M.read (fun env -> M.return (snd env)) + + let decrease_limit = + M.bind M.read (fun st -> + match st with + | _, Unlimited -> M.return () + | env, Limited n when n > 0 -> M.write (env, Limited (n - 1)) + | _ -> M.return ()) + ;; + + let ( >>= ) = M.bind + let ( let* ) = bind + + let eval_unop operator expr = + match operator, expr with + | Ast.Neg, Int e -> return (Int (-e)) + | Ast.Neg, _ -> fail (TypeMismatch ("int", show_value_type expr)) + | Ast.Not, Bool e -> return (Bool (not e)) + | Ast.Not, _ -> fail (TypeMismatch ("bool", show_value_type expr)) + ;; + + let eval_binop operator lhs rhs = + match operator, lhs, rhs with + | Ast.Add, Int l, Int r -> return (Int (l + r)) + | Ast.Sub, Int l, Int r -> return (Int (l - r)) + | Ast.Mul, Int l, Int r -> return (Int (l * r)) + | Ast.Div, Int _, Int r when r = 0 -> fail ZeroDivision + | Ast.Div, Int l, Int r -> return (Int (l / r)) + | Ast.Mod, Int _, Int r when r = 0 -> fail ZeroDivision + | Ast.Mod, Int l, Int r -> return (Int (l mod r)) + | Ast.And, Bool l, Bool r -> return (Bool (l && r)) + | Ast.Or, Bool l, Bool r -> return (Bool (l || r)) + | Ast.Equal, Int l, Int r -> return (Bool (l = r)) + | Ast.Equal, Bool l, Bool r -> return (Bool (l = r)) + | Ast.NotEqual, Int l, Int r -> return (Bool (l <> r)) + | Ast.NotEqual, Bool l, Bool r -> return (Bool (l <> r)) + | Ast.Less, Int l, Int r -> return (Bool (l < r)) + | Ast.LessEqual, Int l, Int r -> return (Bool (l <= r)) + | Ast.Greater, Int l, Int r -> return (Bool (l > r)) + | Ast.GreaterEqual, Int l, Int r -> return (Bool (l >= r)) + | _, _, _ -> fail (TypeMismatch (show_value_type lhs, show_value_type rhs)) + ;; + + let rec lookup name vars = + match name with + | Ast.Wildcard -> None + | Ast.Real name_str -> + (match vars with + | [] -> None + | (Ast.Real str, value) :: _ when str = name_str -> Some value + | _ :: tl -> lookup name tl) + ;; + + let rec eval expr = + decrease_limit + >>= fun _ -> + get_limit + >>= fun limit -> + (match limit with + | Limited 0 -> fail ExhaustedSteps + | _ -> return ()) + >>= fun _ -> + match expr with + | Ast.Unit -> return Unit + | Ast.Int int -> return (Int int) + | Ast.Bool bool -> return (Bool bool) + | Ast.Var name -> + get_vars + >>= fun vars -> + (match lookup name vars with + | None -> fail (UnboundVariable name) + | Some v -> return v) + | Ast.Tuple (fst, snd, tl) -> + let* v1 = eval fst in + let* v2 = eval snd in + let rec eval_list acc = function + | [] -> return (List.rev acc) + | e :: rest -> + let* v = eval e in + eval_list (v :: acc) rest + in + let* vs = eval_list [] tl in + return (Tuple (v1, v2, vs)) + | Ast.UnaryOp (op, expr) -> + let* v = eval expr in + eval_unop op v + | Ast.BinaryOp (op, left, right) -> + let* v1 = eval left in + let* v2 = eval right in + eval_binop op v1 v2 + | Ast.IfThenElse (cond, e1, e2) -> + let* vcond = eval cond in + (match vcond with + | Bool true -> eval e1 + | Bool false -> eval e2 + | _ -> fail (TypeMismatch ("bool", show_value_type vcond))) + | Ast.LetExpr (Ast.Let, name, e1, e2) -> + let* v1 = eval e1 in + get_vars + >>= fun vars -> + set_vars ((name, v1) :: vars) + >>= fun _ -> + let* v2 = eval e2 in + get_vars >>= fun _ -> set_vars vars >>= fun _ -> return v2 + | Ast.LetExpr (Ast.LetRec, name, e1, e2) -> + (match e1 with + | Ast.Abstraction _ -> + get_limit + >>= fun limit -> + get_vars + >>= fun vars -> + let rec v = Closure (e1, ((name, v) :: vars, limit)) in + set_vars ((name, v) :: vars) + >>= fun () -> + let* v2 = eval e2 in + get_vars >>= fun _ -> set_vars vars >>= fun () -> return v2 + | _ -> fail InvalidLet) + | Ast.Abstraction _ as abs -> + get_limit + >>= fun limit -> get_vars >>= fun vars -> return (Closure (abs, (vars, limit))) + | Ast.Application (expr1, expr2) -> + let* v1 = eval expr1 in + let* v2 = eval expr2 in + (match v1 with + | Closure (Ast.Abstraction (arg, expr), env) -> + get_vars + >>= fun saved -> + set_vars ((arg, v2) :: fst env) + >>= fun _ -> + let* result = eval expr in + get_vars >>= fun _ -> set_vars saved >>= fun _ -> return result + | BuiltinAbstraction f -> + (match f v2 with + | Eval v -> return v + | EvalError e -> fail e) + | _ -> fail InvalidApplication) + ;; +end diff --git a/Lazarev/lib/interpreter.mli b/Lazarev/lib/interpreter.mli new file mode 100644 index 00000000..29ff3e79 --- /dev/null +++ b/Lazarev/lib/interpreter.mli @@ -0,0 +1,44 @@ +[@@@ocaml.text "/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "/*"] + +(** Type for interpreter's error *) +type error = + | ExhaustedSteps (** When step limit is reached *) + | ZeroDivision (** When divider has been evaluated to zero *) + | InvalidApplication (** When application is not valid *) + | InvalidLet (** When recursive let statement is used wrongly *) + | UnboundVariable of Ast.name (** When provided name is not a variable *) + | TypeMismatch of string * string (** When expected type differs from evaluated type *) + +(** Type for evaluation result *) +type 'a result = + | Eval of 'a + | EvalError of error + +(** Type for step limit *) +type step_limit = + | Unlimited (** Count of steps is not bounded *) + | Limited of int (** Count of steps is bounded and how many steps remaining *) + +(** Type for interpreter's evaluated value *) +type value = + | Unit + | Int of int + | Bool of bool + | Tuple of value * value * value list + | Closure of Ast.t * env + | BuiltinAbstraction of (value -> value result) + +(** Type for interpreter's enviropment *) +and env = (Ast.name * value) list * step_limit + +(** Obtain empty enviropment with built-in functions *) +val empty_env : env + +val show_value_type : value -> string +val show_value : value -> string From 1c1cf92c27dcf62d2631b02b1cce04edea3c721b Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 11 Apr 2026 01:45:30 +0300 Subject: [PATCH 08/28] Refactor library code Signed-off-by: Andrew Lazarev --- Lazarev/lib/ast.ml | 63 ++++++++---------- Lazarev/lib/ast.mli | 5 +- Lazarev/lib/interpreter.ml | 125 ++++++++++++++++++++++++------------ Lazarev/lib/interpreter.mli | 17 +++-- Lazarev/lib/parser.ml | 6 +- Lazarev/lib/parser.mli | 6 +- Lazarev/lib/utils.mli | 18 +----- 7 files changed, 131 insertions(+), 109 deletions(-) diff --git a/Lazarev/lib/ast.ml b/Lazarev/lib/ast.ml index 1373db5b..abaf2fe4 100644 --- a/Lazarev/lib/ast.ml +++ b/Lazarev/lib/ast.ml @@ -45,7 +45,6 @@ type t = | UnaryOp of unary_operation * t | BinaryOp of binary_operation * t * t | IfThenElse of t * t * t - | LetStatement of let_mnemonic * name * t | LetExpr of let_mnemonic * name * t * t | Abstraction of name * t | Application of t * t @@ -55,7 +54,7 @@ let show_name = function | Real name -> name ;; -let rec show_ast = function +let rec show_ast_verbose = function | Unit -> "unit" | Int value -> string_of_int value | Bool value -> string_of_bool value @@ -63,37 +62,32 @@ let rec show_ast = function | Tuple (first, second, rest) -> Format.sprintf "Tuple(%s)" - (String.concat ", " (List.map show_ast (first :: second :: rest))) + (String.concat ", " (List.map show_ast_verbose (first :: second :: rest))) | UnaryOp (op, expr) -> - Format.sprintf "%s(%s)" (show_unary_operation op) (show_ast expr) + Format.sprintf "%s(%s)" (show_unary_operation op) (show_ast_verbose expr) | BinaryOp (op, left, right) -> Format.sprintf "%s(%s, %s)" (show_binary_operation op) - (show_ast left) - (show_ast right) + (show_ast_verbose left) + (show_ast_verbose right) | IfThenElse (cond, then_expr, else_expr) -> Format.sprintf "IfThenElse(%s, %s, %s)" - (show_ast cond) - (show_ast then_expr) - (show_ast else_expr) - | LetStatement (rf, name, statement) -> - Format.sprintf - "%s(%s, %s)" - (show_let_mnemonic rf) - (show_name name) - (show_ast statement) + (show_ast_verbose cond) + (show_ast_verbose then_expr) + (show_ast_verbose else_expr) | LetExpr (rf, name, lhs, rhs) -> Format.sprintf "%s(%s, %s, %s)" (show_let_mnemonic rf) (show_name name) - (show_ast lhs) - (show_ast rhs) + (show_ast_verbose lhs) + (show_ast_verbose rhs) | Abstraction (name, expr) -> - Format.sprintf "Abs(%s, %s)" (show_name name) (show_ast expr) - | Application (lhs, rhs) -> Format.sprintf "App(%s, %s)" (show_ast lhs) (show_ast rhs) + Format.sprintf "Abs(%s, %s)" (show_name name) (show_ast_verbose expr) + | Application (lhs, rhs) -> + Format.sprintf "App(%s, %s)" (show_ast_verbose lhs) (show_ast_verbose rhs) ;; let show_pretty_unary_operation = function @@ -122,7 +116,7 @@ let show_pretty_rec_flag = function | LetRec -> "let rec" ;; -let rec show_pretty_ast = function +let rec show_ast = function | Unit -> "()" | Int value -> string_of_int value | Bool value -> string_of_bool value @@ -130,36 +124,29 @@ let rec show_pretty_ast = function | Tuple (first, second, rest) -> Format.sprintf "(%s)" - (String.concat ", " (List.map show_pretty_ast (first :: second :: rest))) + (String.concat ", " (List.map show_ast (first :: second :: rest))) | UnaryOp (op, expr) -> - Format.sprintf "%s(%s)" (show_pretty_unary_operation op) (show_pretty_ast expr) + Format.sprintf "%s(%s)" (show_pretty_unary_operation op) (show_ast expr) | BinaryOp (op, left, right) -> Format.sprintf "(%s %s %s)" - (show_pretty_ast left) + (show_ast left) (show_pretty_binary_operation op) - (show_pretty_ast right) + (show_ast right) | IfThenElse (cond, then_expr, else_expr) -> Format.sprintf "if (%s) then (%s) else (%s)" - (show_pretty_ast cond) - (show_pretty_ast then_expr) - (show_pretty_ast else_expr) - | LetStatement (rf, name, statement) -> - Format.sprintf - "%s %s = (%s)" - (show_pretty_rec_flag rf) - (show_name name) - (show_pretty_ast statement) + (show_ast cond) + (show_ast then_expr) + (show_ast else_expr) | LetExpr (rf, name, lhs, rhs) -> Format.sprintf "%s %s = (%s) in (%s)" (show_pretty_rec_flag rf) (show_name name) - (show_pretty_ast lhs) - (show_pretty_ast rhs) + (show_ast lhs) + (show_ast rhs) | Abstraction (var, expr) -> - Format.sprintf "fun %s -> %s" (show_name var) (show_pretty_ast expr) - | Application (lhs, rhs) -> - Format.sprintf "((%s) (%s))" (show_pretty_ast lhs) (show_pretty_ast rhs) + Format.sprintf "fun %s -> %s" (show_name var) (show_ast expr) + | Application (lhs, rhs) -> Format.sprintf "((%s) (%s))" (show_ast lhs) (show_ast rhs) ;; diff --git a/Lazarev/lib/ast.mli b/Lazarev/lib/ast.mli index 07b8059b..cbd2a4a9 100644 --- a/Lazarev/lib/ast.mli +++ b/Lazarev/lib/ast.mli @@ -47,13 +47,12 @@ type t = | UnaryOp of unary_operation * t (** Unary operation [..y] *) | BinaryOp of binary_operation * t * t (** Binary operation [x .. y] *) | IfThenElse of t * t * t (** If-then-else expression [if ... then ... else ...] *) - | LetStatement of let_mnemonic * name * t (** Let statement [let x = ...] *) | LetExpr of let_mnemonic * name * t * t (** Let expression [let x = ... in ...] *) | Abstraction of name * t (** Lambda abstraction [fun x -> ...] *) | Application of t * t (** Application [(f x)] *) (** Shows AST in verbose format *) -val show_ast : t -> string +val show_ast_verbose : t -> string (** Shows AST in human readable format *) -val show_pretty_ast : t -> string +val show_ast : t -> string diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml index 75699c10..dacb93c3 100644 --- a/Lazarev/lib/interpreter.ml +++ b/Lazarev/lib/interpreter.ml @@ -7,12 +7,13 @@ [@@@ocaml.text "/*"] type error = - | ExhaustedSteps + | LimitError | ZeroDivision | InvalidApplication | InvalidLet | UnboundVariable of Ast.name - | TypeMismatch of string * string + | TypeMismatch of string + | TypesMismatch of string * string type 'a result = | Eval of 'a @@ -48,53 +49,63 @@ module State : Utils.STATE_MONAD = struct let run func state = func state end -let show_value_type = function +let rec show_value_type = function | Unit -> "unit" | Int _ -> "int" | Bool _ -> "bool" - | Tuple _ -> "" + | Tuple (t1, t2, ts) -> String.concat " * " (List.map show_value_type (t1 :: t2 :: ts)) | Closure _ -> "" | BuiltinAbstraction _ -> "" ;; -let show_value = function +let rec show_value = function | Unit -> "()" | Int int -> string_of_int int | Bool bool -> string_of_bool bool + | Tuple (v1, v2, vs) -> String.concat " * " (List.map show_value (v1 :: v2 :: vs)) | _ -> "" ;; -module Eval (M : Utils.STATE_MONAD) = struct - let return x = M.return (Eval x) - let fail e = M.return (EvalError e) +module Interpreter (ST : Utils.STATE_MONAD) = struct + let return x = ST.return (Eval x) + let fail e = ST.return (EvalError e) - let bind x transform = - M.bind x (function + (* Two different bind operators here *) + (* '>>=' is used for State *) + (* 'let*' is used for Eval *) + + let ( >>= ) = ST.bind + + let ( let* ) x transform = + ST.bind x (function | Eval x -> transform x - | EvalError e -> M.return (EvalError e)) + | EvalError e -> ST.return (EvalError e)) ;; - let get_vars = M.bind M.read (fun env -> M.return (fst env)) - let set_vars vars = M.bind M.read (fun env -> M.write (vars, snd env)) - let get_limit = M.bind M.read (fun env -> M.return (snd env)) + let get_vars = ST.bind ST.read (fun env -> ST.return (fst env)) + let get_limit = ST.bind ST.read (fun env -> ST.return (snd env)) - let decrease_limit = - M.bind M.read (fun st -> - match st with - | _, Unlimited -> M.return () - | env, Limited n when n > 0 -> M.write (env, Limited (n - 1)) - | _ -> M.return ()) + let update_vars var value = + ST.bind ST.read (fun (vars, limit) -> ST.write ((var, value) :: vars, limit)) ;; - let ( >>= ) = M.bind - let ( let* ) = bind + let set_vars vars = ST.bind ST.read (fun env -> ST.write (vars, snd env)) + + let update_limit = + ST.bind ST.read (fun st -> + match st with + | _, Unlimited -> ST.return Unlimited + | env, Limited n when n > 0 -> + ST.write (env, Limited (n - 1)) >>= fun _ -> ST.return (Limited (n - 1)) + | _, Limited n -> ST.return (Limited n)) + ;; let eval_unop operator expr = match operator, expr with | Ast.Neg, Int e -> return (Int (-e)) - | Ast.Neg, _ -> fail (TypeMismatch ("int", show_value_type expr)) + | Ast.Neg, _ -> fail (TypeMismatch (show_value_type expr)) | Ast.Not, Bool e -> return (Bool (not e)) - | Ast.Not, _ -> fail (TypeMismatch ("bool", show_value_type expr)) + | Ast.Not, _ -> fail (TypeMismatch (show_value_type expr)) ;; let eval_binop operator lhs rhs = @@ -116,7 +127,7 @@ module Eval (M : Utils.STATE_MONAD) = struct | Ast.LessEqual, Int l, Int r -> return (Bool (l <= r)) | Ast.Greater, Int l, Int r -> return (Bool (l > r)) | Ast.GreaterEqual, Int l, Int r -> return (Bool (l >= r)) - | _, _, _ -> fail (TypeMismatch (show_value_type lhs, show_value_type rhs)) + | _, _, _ -> fail (TypesMismatch (show_value_type lhs, show_value_type rhs)) ;; let rec lookup name vars = @@ -130,12 +141,10 @@ module Eval (M : Utils.STATE_MONAD) = struct ;; let rec eval expr = - decrease_limit - >>= fun _ -> - get_limit + update_limit >>= fun limit -> (match limit with - | Limited 0 -> fail ExhaustedSteps + | Limited 0 -> fail LimitError | _ -> return ()) >>= fun _ -> match expr with @@ -171,27 +180,27 @@ module Eval (M : Utils.STATE_MONAD) = struct (match vcond with | Bool true -> eval e1 | Bool false -> eval e2 - | _ -> fail (TypeMismatch ("bool", show_value_type vcond))) + | _ -> fail (TypeMismatch (show_value_type vcond))) | Ast.LetExpr (Ast.Let, name, e1, e2) -> let* v1 = eval e1 in get_vars - >>= fun vars -> - set_vars ((name, v1) :: vars) + >>= fun saved_vars -> + update_vars name v1 >>= fun _ -> let* v2 = eval e2 in - get_vars >>= fun _ -> set_vars vars >>= fun _ -> return v2 + get_vars >>= fun _ -> set_vars saved_vars >>= fun _ -> return v2 | Ast.LetExpr (Ast.LetRec, name, e1, e2) -> (match e1 with | Ast.Abstraction _ -> get_limit >>= fun limit -> get_vars - >>= fun vars -> - let rec v = Closure (e1, ((name, v) :: vars, limit)) in - set_vars ((name, v) :: vars) - >>= fun () -> + >>= fun saved_vars -> + let rec v = Closure (e1, ((name, v) :: saved_vars, limit)) in + update_vars name v + >>= fun _ -> let* v2 = eval e2 in - get_vars >>= fun _ -> set_vars vars >>= fun () -> return v2 + get_vars >>= fun _ -> set_vars saved_vars >>= fun _ -> return v2 | _ -> fail InvalidLet) | Ast.Abstraction _ as abs -> get_limit @@ -202,11 +211,11 @@ module Eval (M : Utils.STATE_MONAD) = struct (match v1 with | Closure (Ast.Abstraction (arg, expr), env) -> get_vars - >>= fun saved -> + >>= fun saved_vars -> set_vars ((arg, v2) :: fst env) >>= fun _ -> let* result = eval expr in - get_vars >>= fun _ -> set_vars saved >>= fun _ -> return result + get_vars >>= fun _ -> set_vars saved_vars >>= fun _ -> return result | BuiltinAbstraction f -> (match f v2 with | Eval v -> return v @@ -214,3 +223,39 @@ module Eval (M : Utils.STATE_MONAD) = struct | _ -> fail InvalidApplication) ;; end + +let initial_env ?(steps = Unlimited) = + let print = + BuiltinAbstraction + (function + | Unit -> + print_string "()"; + Eval Unit + | Int int -> + print_int int; + Eval Unit + | Bool bool -> + print_string (string_of_bool bool); + Eval Unit + | _ -> EvalError InvalidApplication) + in + let first = + BuiltinAbstraction + (function + | Tuple (v1, _, _) -> Eval v1 + | _ -> EvalError InvalidApplication) + in + let second = + BuiltinAbstraction + (function + | Tuple (_, v1, vs) when vs = [] -> Eval v1 + | Tuple (_, v1, v2 :: vs) -> Eval (Tuple (v1, v2, vs)) + | _ -> EvalError InvalidApplication) + in + [ "print", print; "fst", first; "snd", second ], steps +;; + +let run env expr = + let module E = Interpreter (State) in + State.run (E.eval expr) env |> snd +;; diff --git a/Lazarev/lib/interpreter.mli b/Lazarev/lib/interpreter.mli index 29ff3e79..d3f6e0e4 100644 --- a/Lazarev/lib/interpreter.mli +++ b/Lazarev/lib/interpreter.mli @@ -8,12 +8,13 @@ (** Type for interpreter's error *) type error = - | ExhaustedSteps (** When step limit is reached *) + | LimitError (** When step limit is reached *) | ZeroDivision (** When divider has been evaluated to zero *) | InvalidApplication (** When application is not valid *) | InvalidLet (** When recursive let statement is used wrongly *) | UnboundVariable of Ast.name (** When provided name is not a variable *) - | TypeMismatch of string * string (** When expected type differs from evaluated type *) + | TypeMismatch of string (** When type is invalid *) + | TypesMismatch of string * string (** When pair of types is invalid *) (** Type for evaluation result *) type 'a result = @@ -38,7 +39,13 @@ type value = and env = (Ast.name * value) list * step_limit (** Obtain empty enviropment with built-in functions *) -val empty_env : env +val initial_env : ?steps:step_limit -> env -val show_value_type : value -> string -val show_value : value -> string +(** Runs the interpreter *) +val run : env -> Ast.t -> value result + +(** Shows result in human-readable format *) +val show_result : value result -> string + +(** Shows error in human-readable format *) +val show_error : error -> string diff --git a/Lazarev/lib/parser.ml b/Lazarev/lib/parser.ml index 8102c18d..cd52e335 100644 --- a/Lazarev/lib/parser.ml +++ b/Lazarev/lib/parser.ml @@ -267,9 +267,9 @@ let wrap_result = function | ParseError _ as e -> e ;; -let parse_one string = - let atom = ws0 *> atom <* ws0 in - chars_of_string string |> atom |> wrap_result +let parse_line line = + let expr = ws0 *> atom <* ws0 in + chars_of_string line |> expr |> wrap_result ;; let show_error = function diff --git a/Lazarev/lib/parser.mli b/Lazarev/lib/parser.mli index 17e211f8..d72b4218 100644 --- a/Lazarev/lib/parser.mli +++ b/Lazarev/lib/parser.mli @@ -17,11 +17,11 @@ type 'a result = | Parsed of 'a * char list | ParseError of error +(** Parses one expression *) +val parse_line : string -> Ast.t result + (** Shows error in human readable format *) val show_error : error -> string (** Shows result in human readable format *) val show_result : Ast.t result -> string - -(** Parse expression *) -val parse_one : string -> Ast.t result diff --git a/Lazarev/lib/utils.mli b/Lazarev/lib/utils.mli index 0b0e9bfa..05fbc9da 100644 --- a/Lazarev/lib/utils.mli +++ b/Lazarev/lib/utils.mli @@ -6,22 +6,6 @@ [@@@ocaml.text "*/*"] -module type MONAD = sig - type 'a t - - val return : 'a -> 'a t - val bind : 'a t -> ('a -> 'b t) -> 'b t -end - -module type MONAD_ERROR = sig - type ('e, 'a) t - - val return : 'a -> ('e, 'a) t - val bind : ('e, 'a) t -> ('a -> ('e, 'b) t) -> ('e, 'b) t - val fail : 'e -> ('e, 'a) t - val catch : ('e, 'a) t -> ('e -> ('e, 'a) t) -> ('e, 'a) t -end - module type READER_MONAD = sig type ('s, 'a) t @@ -42,7 +26,7 @@ end module type STATE_MONAD = sig include READER_MONAD - include WRITER_MONAD with type ('s, 'a) t := ('s, 'a) t + val write : 's -> ('s, unit) t val run : ('st, 'a) t -> 'st -> 'st * 'a end From 39cf06c57ed5078a86ca8fd87a57d148747600ed Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 01:10:42 +0300 Subject: [PATCH 09/28] Add REPL Signed-off-by: Andrew Lazarev --- Lazarev/bin/REPL.ml | 42 ++++++++++++++++++++++++++++++++++++++++++ Lazarev/bin/REPL.mli | 9 +++++++++ Lazarev/bin/dune | 10 ++++++++++ 3 files changed, 61 insertions(+) create mode 100644 Lazarev/bin/REPL.ml create mode 100644 Lazarev/bin/REPL.mli create mode 100644 Lazarev/bin/dune diff --git a/Lazarev/bin/REPL.ml b/Lazarev/bin/REPL.ml new file mode 100644 index 00000000..0b2d6d85 --- /dev/null +++ b/Lazarev/bin/REPL.ml @@ -0,0 +1,42 @@ +[@@@ocaml.text "*/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "*/*"] + +module Arg = Stdlib.Arg +module Ast = Mini_ml_lib.Ast +module Interpreter = Mini_ml_lib.Interpreter +module Parser = Mini_ml_lib.Parser + +type opts = { mutable env : Interpreter.env } + +let get_input () = + try Some (read_line ()) with + | End_of_file -> None +;; + +let run env = + let line = get_input () in + match line with + | None -> () + | Some input -> + (match Parser.parse_line input with + | Parser.ParseError error -> Parser.show_error error |> print_endline + | Parser.Parsed (ast, _) -> + Interpreter.run env ast |> Interpreter.show_result |> print_endline) +;; + +let () = + let options = { env = Interpreter.new_env } in + let args = + [ ( "--steps" + , Arg.Int (fun n -> options.env <- Interpreter.new_env_limited n) + , "Set maximum number of evaluation steps (default: 1000)" ) + ] + in + Arg.parse args (fun _ -> ()) ""; + run options.env +;; diff --git a/Lazarev/bin/REPL.mli b/Lazarev/bin/REPL.mli new file mode 100644 index 00000000..dc53261a --- /dev/null +++ b/Lazarev/bin/REPL.mli @@ -0,0 +1,9 @@ +[@@@ocaml.text "*/*"] + +(** Copyright 2021-2024, Kakadu and contributors *) + +(** SPDX-License-Identifier: LGPL-3.0-or-later *) + +[@@@ocaml.text "*/*"] + +(* This file is intentionally empty *) diff --git a/Lazarev/bin/dune b/Lazarev/bin/dune new file mode 100644 index 00000000..181f5748 --- /dev/null +++ b/Lazarev/bin/dune @@ -0,0 +1,10 @@ +(executable + (name REPL) + (public_name REPL) + (libraries mini_ml_lib angstrom) + (instrumentation + (backend bisect_ppx)) + (modules REPL)) + +(cram + (deps ./REPL.exe %{bin:REPL})) From 110885403e9b36f905739db3f718b3b7f8fce22f Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 03:52:49 +0300 Subject: [PATCH 10/28] Fix interpreter to respect step limit Signed-off-by: Andrew Lazarev --- Lazarev/lib/interpreter.ml | 116 ++++++++++++++++++++++-------------- Lazarev/lib/interpreter.mli | 13 ++-- 2 files changed, 79 insertions(+), 50 deletions(-) diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml index dacb93c3..81b54a0b 100644 --- a/Lazarev/lib/interpreter.ml +++ b/Lazarev/lib/interpreter.ml @@ -1,10 +1,10 @@ -[@@@ocaml.text "/*"] +[@@@ocaml.text "*/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "/*"] +[@@@ocaml.text "*/*"] type error = | LimitError @@ -24,7 +24,6 @@ type step_limit = | Limited of int type env = (Ast.name * value) list * step_limit -and variables = (Ast.name * value) list and value = | Unit @@ -34,7 +33,9 @@ and value = | Closure of Ast.t * env | BuiltinAbstraction of (value -> value result) -module State : Utils.STATE_MONAD = struct +type variables = (Ast.name * value) list + +module InterpreterState : Utils.STATE_MONAD = struct type ('s, 'a) t = 's -> 's * 'a let return x st = st, x @@ -58,14 +59,6 @@ let rec show_value_type = function | BuiltinAbstraction _ -> "" ;; -let rec show_value = function - | Unit -> "()" - | Int int -> string_of_int int - | Bool bool -> string_of_bool bool - | Tuple (v1, v2, vs) -> String.concat " * " (List.map show_value (v1 :: v2 :: vs)) - | _ -> "" -;; - module Interpreter (ST : Utils.STATE_MONAD) = struct let return x = ST.return (Eval x) let fail e = ST.return (EvalError e) @@ -79,7 +72,7 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct let ( let* ) x transform = ST.bind x (function | Eval x -> transform x - | EvalError e -> ST.return (EvalError e)) + | EvalError e -> fail e) ;; let get_vars = ST.bind ST.read (fun env -> ST.return (fst env)) @@ -94,10 +87,9 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct let update_limit = ST.bind ST.read (fun st -> match st with - | _, Unlimited -> ST.return Unlimited - | env, Limited n when n > 0 -> - ST.write (env, Limited (n - 1)) >>= fun _ -> ST.return (Limited (n - 1)) - | _, Limited n -> ST.return (Limited n)) + | _, Unlimited -> ST.return () + | env, Limited n when n > 0 -> ST.write (env, Limited (n - 1)) + | _, Limited _ -> ST.return ()) ;; let eval_unop operator expr = @@ -133,20 +125,22 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct let rec lookup name vars = match name with | Ast.Wildcard -> None - | Ast.Real name_str -> + | Ast.Real name' -> (match vars with | [] -> None - | (Ast.Real str, value) :: _ when str = name_str -> Some value + | (Ast.Real str, value) :: _ when String.equal str name' -> Some value | _ :: tl -> lookup name tl) ;; let rec eval expr = - update_limit - >>= fun limit -> - (match limit with - | Limited 0 -> fail LimitError - | _ -> return ()) - >>= fun _ -> + let* _ = + get_limit + >>= fun limit -> + match limit with + | Limited 0 -> fail LimitError + | _ -> return () + in + let* _ = update_limit >>= fun _ -> return () in match expr with | Ast.Unit -> return Unit | Ast.Int int -> return (Int int) @@ -157,16 +151,16 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct (match lookup name vars with | None -> fail (UnboundVariable name) | Some v -> return v) - | Ast.Tuple (fst, snd, tl) -> - let* v1 = eval fst in - let* v2 = eval snd in + | Ast.Tuple (v1, v2, vs) -> + let* v1 = eval v1 in + let* v2 = eval v2 in let rec eval_list acc = function | [] -> return (List.rev acc) | e :: rest -> let* v = eval e in eval_list (v :: acc) rest in - let* vs = eval_list [] tl in + let* vs = eval_list [] vs in return (Tuple (v1, v2, vs)) | Ast.UnaryOp (op, expr) -> let* v = eval expr in @@ -196,11 +190,11 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct >>= fun limit -> get_vars >>= fun saved_vars -> - let rec v = Closure (e1, ((name, v) :: saved_vars, limit)) in - update_vars name v + let rec self = Closure (e1, ((name, self) :: saved_vars, limit)) in + update_vars name self >>= fun _ -> let* v2 = eval e2 in - get_vars >>= fun _ -> set_vars saved_vars >>= fun _ -> return v2 + set_vars saved_vars >>= fun _ -> return v2 | _ -> fail InvalidLet) | Ast.Abstraction _ as abs -> get_limit @@ -215,7 +209,7 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct set_vars ((arg, v2) :: fst env) >>= fun _ -> let* result = eval expr in - get_vars >>= fun _ -> set_vars saved_vars >>= fun _ -> return result + set_vars saved_vars >>= fun _ -> return result | BuiltinAbstraction f -> (match f v2 with | Eval v -> return v @@ -224,38 +218,70 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct ;; end -let initial_env ?(steps = Unlimited) = - let print = +let get_builtins = + let print_int = BuiltinAbstraction (function - | Unit -> - print_string "()"; - Eval Unit | Int int -> - print_int int; + string_of_int int |> print_endline; Eval Unit + | _ -> EvalError InvalidApplication) + in + let print_bool = + BuiltinAbstraction + (function | Bool bool -> - print_string (string_of_bool bool); + string_of_bool bool |> print_endline; Eval Unit | _ -> EvalError InvalidApplication) in - let first = + let get_first = BuiltinAbstraction (function | Tuple (v1, _, _) -> Eval v1 | _ -> EvalError InvalidApplication) in - let second = + let get_second = BuiltinAbstraction (function | Tuple (_, v1, vs) when vs = [] -> Eval v1 | Tuple (_, v1, v2 :: vs) -> Eval (Tuple (v1, v2, vs)) | _ -> EvalError InvalidApplication) in - [ "print", print; "fst", first; "snd", second ], steps + [ Ast.Real "print_int", print_int + ; Ast.Real "print_bool", print_bool + ; Ast.Real "fst", get_first + ; Ast.Real "snd", get_second + ] +;; + +let new_env = get_builtins, Unlimited +let new_env_limited limit = get_builtins, Limited limit + +let show_error = function + | LimitError -> "Steps limit exceeded" + | ZeroDivision -> "Division by zero" + | InvalidApplication -> "Invalid application" + | InvalidLet -> "Invalid let-statement" + | UnboundVariable name -> Format.sprintf "Unbodund variable '%s'" (Ast.show_name name) + | TypeMismatch typ -> Format.sprintf "Type mismatch: '%s'" typ + | TypesMismatch (typ1, typ2) -> Format.sprintf "Types mismatch: '%s' and '%s'" typ1 typ2 +;; + +let show_result result = + let rec show_eval = function + | Unit -> "()" + | Int int -> string_of_int int + | Bool bool -> string_of_bool bool + | Tuple (v1, v2, vs) -> String.concat ", " (List.map show_eval (v1 :: v2 :: vs)) + | Closure _ | BuiltinAbstraction _ -> "?" + in + match result with + | Eval value -> Format.sprintf "%s: %s" (show_value_type value) (show_eval value) + | EvalError error -> Format.sprintf "Error: %s" (show_error error) ;; let run env expr = - let module E = Interpreter (State) in - State.run (E.eval expr) env |> snd + let module I = Interpreter (InterpreterState) in + InterpreterState.run (I.eval expr) env ;; diff --git a/Lazarev/lib/interpreter.mli b/Lazarev/lib/interpreter.mli index d3f6e0e4..cd8e6103 100644 --- a/Lazarev/lib/interpreter.mli +++ b/Lazarev/lib/interpreter.mli @@ -1,10 +1,10 @@ -[@@@ocaml.text "/*"] +[@@@ocaml.text "*/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "/*"] +[@@@ocaml.text "*/*"] (** Type for interpreter's error *) type error = @@ -38,11 +38,14 @@ type value = (** Type for interpreter's enviropment *) and env = (Ast.name * value) list * step_limit -(** Obtain empty enviropment with built-in functions *) -val initial_env : ?steps:step_limit -> env +(** Returns empty enviropment with built-in functions *) +val new_env : env + +(** Returns empty enviropment with steps limit and built-in functions *) +val new_env_limited : int -> env (** Runs the interpreter *) -val run : env -> Ast.t -> value result +val run : env -> Ast.t -> env * value result (** Shows result in human-readable format *) val show_result : value result -> string From dba7ab435e422fcb0992232b89589cd69136944a Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 03:53:12 +0300 Subject: [PATCH 11/28] Fix interpreter to respect step limit 2 Signed-off-by: Andrew Lazarev --- Lazarev/lib/interpreter.ml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml index 81b54a0b..e2061a01 100644 --- a/Lazarev/lib/interpreter.ml +++ b/Lazarev/lib/interpreter.ml @@ -135,8 +135,7 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct let rec eval expr = let* _ = get_limit - >>= fun limit -> - match limit with + >>= function | Limited 0 -> fail LimitError | _ -> return () in From 8d8a15ccc1c53c2f96594d8132abe4081e63a046 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 04:57:43 +0300 Subject: [PATCH 12/28] Add new tests Signed-off-by: Andrew Lazarev --- Lazarev/tests/ast_tests.ml | 18 +-- Lazarev/tests/interpreter.t | 270 ++++++++++++++++++++++++++++++++++ Lazarev/tests/parser_tests.ml | 34 ++--- 3 files changed, 288 insertions(+), 34 deletions(-) diff --git a/Lazarev/tests/ast_tests.ml b/Lazarev/tests/ast_tests.ml index 8cbbf45d..95a82998 100644 --- a/Lazarev/tests/ast_tests.ml +++ b/Lazarev/tests/ast_tests.ml @@ -22,7 +22,7 @@ let div lhs rhs = Ast.BinaryOp (Ast.Div, lhs, rhs) let rem lhs rhs = Ast.BinaryOp (Ast.Mod, lhs, rhs) let expect ast verbose pretty = - Ast.show_ast ast = verbose && Ast.show_pretty_ast ast = pretty + Ast.show_ast_verbose ast = verbose && Ast.show_ast ast = pretty ;; let%test "Unit" = expect Ast.Unit "unit" "()" @@ -92,19 +92,3 @@ let%test "Applications & abstractions" = "App(App(Abs(_, Abs(a, 12)), x1), x2)" "((((fun _ -> fun a -> 12) (x1))) (x2))" ;; - -let let_st name expr = Ast.LetStatement (Ast.Let, name, expr) -let letrec_st name expr = Ast.LetStatement (Ast.LetRec, name, expr) - -let%test "Let 1" = - expect (let_st (name "value") (var "value")) "Let(value, value)" "let value = (value)" -;; - -let%test "Let 2" = - expect - (letrec_st - (name "fact") - (abs (name "n") (app (var "fact") (sub (var "n") (const 1))))) - "LetRec(fact, Abs(n, App(fact, Sub(n, 1))))" - "let rec fact = (fun n -> ((fact) ((n - 1))))" -;; diff --git a/Lazarev/tests/interpreter.t b/Lazarev/tests/interpreter.t index 2ebc0bdd..646af1e9 100644 --- a/Lazarev/tests/interpreter.t +++ b/Lazarev/tests/interpreter.t @@ -8,3 +8,273 @@ Use `dune promote` after you change things that should runned If you need to put sample program and use it both in your interpreter and preinstalled one, you could put it into separate file. Thise will need stanza `(cram (deps demo_input.txt))` in the dune file + +Test with no input + + $ ../bin/REPL.exe --help < 12 + 3 + int: 15 + + $ ../bin/REPL.exe < -9 + 14 + int: 5 + + $ ../bin/REPL.exe < -9 * 10 - 10 + int: -100 + + $ ../bin/REPL.exe < 22 + 22 * 22 + int: 506 + + $ ../bin/REPL.exe < (22 + 22) * 2 + int: 88 + + $ ../bin/REPL.exe < 1 / 24 + int: 0 + + $ ../bin/REPL.exe < 47 mod 4 + int: 3 + + $ ../bin/REPL.exe < 11 / (2 + 2 - (8 / 2)) + 1 + Error: Division by zero + + $ ../bin/REPL.exe < (42) mod (0) + Error: Division by zero + + $ ../bin/REPL.exe --steps 3 < 1 + 2 + 3 + 4 + 5 + Error: Steps limit exceeded + + $ ../bin/REPL.exe < ((1) / (true)) + Error: Types mismatch: 'int' and 'bool' + +Test logical & compare operations + + $ ../bin/REPL.exe < true || false + bool: true + + $ ../bin/REPL.exe < !true && false + bool: false + + $ ../bin/REPL.exe < !42 + Error: Type mismatch: 'int' + + $ ../bin/REPL.exe --steps 1 < !(true || false && false && true) + Error: Steps limit exceeded + + $ ../bin/REPL.exe < 2 > 1 <> false + bool: true + + $ ../bin/REPL.exe < 45 > 100 = (33 <= 33) + bool: false + + $ ../bin/REPL.exe < !(true && false) = (!true || !false) + bool: true + + $ ../bin/REPL.exe < if (true <> false) then (4 >= 2) else 42 + bool: true + + $ ../bin/REPL.exe < if (true <> false) then -42 else 42 + int: -42 + +Test variables + + $ ../bin/REPL.exe < a + b + Error: Unbound variable 'a' + +Test abstraction & application + + $ ../bin/REPL.exe < (fun x -> (x + 1) 1) + int: 2 + + $ ../bin/REPL.exe < (fun x y -> (x + y) 55 45) + int: 100 + + $ ../bin/REPL.exe < (fun x y -> ((x + 10), (y - 10))) @@ 100 @@ 200 + int * int: 110, 190 + + $ ../bin/REPL.exe < ((fun _ x -> x) 100 200) + int: 200 + + $ ../bin/REPL.exe < ((fun x -> x) _) + Error: Unbound variable '_' + + $ ../bin/REPL.exe --multiline < (print_int 100) + > (print_bool false) + 100 + unit: () + false + unit: () + + $ ../bin/REPL.exe --multiline < print_int + > print_bool + > (fst, snd) + : ? + : ? + * : ?, ? + + $ ../bin/REPL.exe --multiline < (print_hoho 100) + > ((1 + 1) 100) + Error: Unbound variable 'print_hoho' + Error: Invalid application + +Test tuples of different types + + $ ../bin/REPL.exe < (1, 2, true, 3) + int * int * bool * int: 1, 2, true, 3 + + $ ../bin/REPL.exe < (1, (2 + 3), (true || false), (4 + 5)) + int * int * bool * int: 1, 5, true, 9 + + $ ../bin/REPL.exe < (fun _ -> 213, fun x -> (x + 1)) + * : ?, ? + + $ ../bin/REPL.exe < ((11 + 2), (5 * 4), true) + int * int * bool: 13, 20, true + + $ ../bin/REPL.exe < ((5 mod 2), false) * (1, 2) + Error: Types mismatch: 'int * bool' and 'int * int' + +Test if-then-else statement + + $ ../bin/REPL.exe < if 1 = (2 - 1) then 42 else (print_int 1) + int: 42 + + $ ../bin/REPL.exe < if 1 + 2 <= (2 - 1) then (print_int 1) else 42 + int: 42 + + $ ../bin/REPL.exe < if (1 + 2) then (print_int 1) else 42 + Error: Type mismatch: 'int' + + $ ../bin/REPL.exe < if () then true else false + Error: Type mismatch: 'unit' + +Test non-recursive let statement & builtin abstraction + + $ ../bin/REPL.exe < let a = 512 * 2 - 24 in (print_int a) + 1000 + unit: () + + $ ../bin/REPL.exe --multiline < let a = let _ = (print_int 10) in 1 in let b = (print_bool true) in (a, b) + > let a = let _ = (print_bool false) in false in let b = let _ = (print_int 111) in 111 in (a, b) + 10 + true + int * unit: 1, () + false + 111 + bool * int: false, 111 + + $ ../bin/REPL.exe < let make = fun x y -> (x, y) in let t1 = (make 1 2) in let t2 = ((snd t1), (fst t1)) in (t1, t2) + int * int * int * int: 1, 2, 2, 1 + + $ ../bin/REPL.exe < let id = fun x -> x in ((id false), (id 1)) + bool * int: false, 1 + + $ ../bin/REPL.exe < let a = (let a = (let a = 7389 in a + 11) in a + 600) in a / 20 + int: 400 + + $ ../bin/REPL.exe < let a = 1 in a + b + Error: Unbound variable 'b' + +Test recursive let statement + + $ ../bin/REPL.exe < let rec sum = fun n -> if (n = 0) then 0 else (n + (sum (n - 1))) in (sum 100) + int: 5050 + + $ ../bin/REPL.exe < let rec fact = fun n -> (if (n = 0) then 1 else (n * (fact (n - 1)))) in (fact 6) + int: 720 + + $ ../bin/REPL.exe --steps 10 < let rec fact = fun n -> (if (n = 0) then 1 else (n * (fact (n - 1)))) in (fact 6) + Error: Steps limit exceeded + + $ ../bin/REPL.exe --steps 500 < let rec fact = fun n -> (if (n = 0) then 1 else (n * (fact (n - 1)))) in (fact 6) + int: 720 + + $ ../bin/REPL.exe < let rec fix = fun f s -> (f (fix f) s) in (fix (fun self n -> if (n <= 1) then 1 else (n * (self (n - 1)))) 7) + int: 5040 + + $ ../bin/REPL.exe < let rec fib = fun n -> if (n <= 2) then 1 else ((fib (n - 1)) + (fib (n - 2))) in (fib 8) + int: 21 + + $ ../bin/REPL.exe < let rec fib = fun n -> if (n <= 2) then 1 else ((fib (n - 1)) + (fib (n - 2))) in (fib 20) + int: 6765 + +Test some infinite recursions + + $ ../bin/REPL.exe --steps 1000 < let rec hehe = (fun _ -> (1 + (hehe 1))) in (hehe 1) + Error: Steps limit exceeded + + $ ../bin/REPL.exe --steps 100 < let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega + Error: Steps limit exceeded + + $ ../bin/REPL.exe --steps 1000 < let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega + Error: Steps limit exceeded + + $ ../bin/REPL.exe --steps 100000 < let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega + Error: Steps limit exceeded diff --git a/Lazarev/tests/parser_tests.ml b/Lazarev/tests/parser_tests.ml index eebc5e84..79959248 100644 --- a/Lazarev/tests/parser_tests.ml +++ b/Lazarev/tests/parser_tests.ml @@ -1,18 +1,18 @@ -[@@@ocaml.text "/*"] +[@@@ocaml.text "*/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "/*"] +[@@@ocaml.text "*/*"] open QCheck module Parser = Mini_ml_lib.Parser module Ast = Mini_ml_lib.Ast let parse_and_print input = - (match Parser.parse_one input with - | Parsed (a, _) -> Ast.show_ast a + (match Parser.parse_line input with + | Parsed (a, _) -> Ast.show_ast_verbose a | ParseError e -> Parser.show_error e) |> print_endline ;; @@ -92,10 +92,10 @@ let%expect_test "Invalid expressions" = ;; let same lhs rhs = - match Parser.parse_one lhs with + match Parser.parse_line lhs with | ParseError _ -> false | Parsed (a, _) -> - (match Parser.parse_one rhs with + (match Parser.parse_line rhs with | ParseError _ -> false | Parsed (b, _) -> a = b) ;; @@ -221,16 +221,16 @@ let gen_ast_depth = ;; let gen_ast limit = Gen.sized (fun size -> gen_ast_depth (min size limit)) -let gen_expr = Gen.map Ast.show_pretty_ast (gen_ast 5) +let gen_expr = Gen.map Ast.show_ast (gen_ast 5) let roundtrip_test_1 = Test.make ~name:"Parser round-trip 1" ~count:50 - (make ~print:Ast.show_pretty_ast (gen_ast 7)) + (make ~print:Ast.show_ast (gen_ast 7)) (fun ast -> - let string = Ast.show_pretty_ast ast in - match Parser.parse_one string with + let string = Ast.show_ast ast in + match Parser.parse_line string with | Parsed (a, _) -> ast = a | ParseError _ -> false) ;; @@ -241,8 +241,8 @@ let roundtrip_test_2 = ~count:50 (make ~print:Fun.id gen_expr) (fun expr -> - match Parser.parse_one expr with - | Parsed (a, _) -> expr = Ast.show_pretty_ast a + match Parser.parse_line expr with + | Parsed (a, _) -> expr = Ast.show_ast a | ParseError _ -> false) ;; @@ -252,8 +252,8 @@ let parser_idempotent_test = ~count:20 (make ~print:Fun.id gen_expr) (fun expr -> - let ast1 = Parser.parse_one expr in - let ast2 = Parser.parse_one expr in + let ast1 = Parser.parse_line expr in + let ast2 = Parser.parse_line expr in ast1 = ast2) ;; @@ -261,10 +261,10 @@ let printer_idempotent_test = Test.make ~name:"Printer idempotence" ~count:20 - (make ~print:Ast.show_pretty_ast (gen_ast 10)) + (make ~print:Ast.show_ast (gen_ast 10)) (fun ast -> - let string1 = Ast.show_pretty_ast ast in - let string2 = Ast.show_pretty_ast ast in + let string1 = Ast.show_ast ast in + let string2 = Ast.show_ast ast in string1 = string2) ;; From 60fc4275bf3b5d1c35829de96a70f511efd48316 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 05:00:25 +0300 Subject: [PATCH 13/28] Fix ocaml_text directives Signed-off-by: Andrew Lazarev --- Lazarev/bin/REPL.ml | 33 +++++++++++++++++++++++++++------ Lazarev/bin/REPL.mli | 4 ++-- Lazarev/lib/ast.ml | 4 ++-- Lazarev/lib/ast.mli | 3 +++ Lazarev/lib/interpreter.ml | 6 +++--- Lazarev/lib/interpreter.mli | 4 ++-- Lazarev/lib/parser.ml | 6 +++--- Lazarev/lib/parser.mli | 4 ++-- Lazarev/lib/utils.mli | 4 ++-- 9 files changed, 46 insertions(+), 22 deletions(-) diff --git a/Lazarev/bin/REPL.ml b/Lazarev/bin/REPL.ml index 0b2d6d85..b0d49a7c 100644 --- a/Lazarev/bin/REPL.ml +++ b/Lazarev/bin/REPL.ml @@ -11,14 +11,28 @@ module Ast = Mini_ml_lib.Ast module Interpreter = Mini_ml_lib.Interpreter module Parser = Mini_ml_lib.Parser -type opts = { mutable env : Interpreter.env } +type opts = + { mutable env : Interpreter.env + ; mutable multiline : bool + } let get_input () = try Some (read_line ()) with | End_of_file -> None ;; -let run env = +let run_one env = + let line = get_input () in + match line with + | None -> print_endline "No input" + | Some input -> + (match Parser.parse_line input with + | Parser.ParseError error -> Parser.show_error error |> print_endline + | Parser.Parsed (ast, _) -> + Interpreter.run env ast |> snd |> Interpreter.show_result |> print_endline) +;; + +let rec run_many env = let line = get_input () in match line with | None -> () @@ -26,17 +40,24 @@ let run env = (match Parser.parse_line input with | Parser.ParseError error -> Parser.show_error error |> print_endline | Parser.Parsed (ast, _) -> - Interpreter.run env ast |> Interpreter.show_result |> print_endline) + let eval = Interpreter.run env ast in + eval |> snd |> Interpreter.show_result |> print_endline; + eval |> fst |> run_many) ;; let () = - let options = { env = Interpreter.new_env } in + let options = { env = Interpreter.new_env; multiline = false } in let args = [ ( "--steps" , Arg.Int (fun n -> options.env <- Interpreter.new_env_limited n) , "Set maximum number of evaluation steps (default: 1000)" ) + ; ( "--multiline" + , Arg.Unit (fun _ -> options.multiline <- true) + , "Enable multiline input for read eval print loop" ) ] in - Arg.parse args (fun _ -> ()) ""; - run options.env + Arg.parse args (fun _ -> ()) "An interpreter for ML-like language"; + match options.multiline with + | false -> run_one options.env + | true -> run_many options.env ;; diff --git a/Lazarev/bin/REPL.mli b/Lazarev/bin/REPL.mli index dc53261a..639d1975 100644 --- a/Lazarev/bin/REPL.mli +++ b/Lazarev/bin/REPL.mli @@ -1,9 +1,9 @@ -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (* This file is intentionally empty *) diff --git a/Lazarev/lib/ast.ml b/Lazarev/lib/ast.ml index abaf2fe4..111581a5 100644 --- a/Lazarev/lib/ast.ml +++ b/Lazarev/lib/ast.ml @@ -1,10 +1,10 @@ -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] type name = | Wildcard diff --git a/Lazarev/lib/ast.mli b/Lazarev/lib/ast.mli index cbd2a4a9..e1b66c4f 100644 --- a/Lazarev/lib/ast.mli +++ b/Lazarev/lib/ast.mli @@ -56,3 +56,6 @@ val show_ast_verbose : t -> string (** Shows AST in human readable format *) val show_ast : t -> string + +(** Shows name of any named entity in AST *) +val show_name : name -> string diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml index e2061a01..1b5e25dc 100644 --- a/Lazarev/lib/interpreter.ml +++ b/Lazarev/lib/interpreter.ml @@ -1,10 +1,10 @@ -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] type error = | LimitError @@ -262,7 +262,7 @@ let show_error = function | ZeroDivision -> "Division by zero" | InvalidApplication -> "Invalid application" | InvalidLet -> "Invalid let-statement" - | UnboundVariable name -> Format.sprintf "Unbodund variable '%s'" (Ast.show_name name) + | UnboundVariable name -> Format.sprintf "Unbound variable '%s'" (Ast.show_name name) | TypeMismatch typ -> Format.sprintf "Type mismatch: '%s'" typ | TypesMismatch (typ1, typ2) -> Format.sprintf "Types mismatch: '%s' and '%s'" typ1 typ2 ;; diff --git a/Lazarev/lib/interpreter.mli b/Lazarev/lib/interpreter.mli index cd8e6103..5ada1a6c 100644 --- a/Lazarev/lib/interpreter.mli +++ b/Lazarev/lib/interpreter.mli @@ -1,10 +1,10 @@ -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (** Type for interpreter's error *) type error = diff --git a/Lazarev/lib/parser.ml b/Lazarev/lib/parser.ml index cd52e335..782558bb 100644 --- a/Lazarev/lib/parser.ml +++ b/Lazarev/lib/parser.ml @@ -1,10 +1,10 @@ -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] type error = | UnexpectedEnd @@ -128,7 +128,7 @@ let identifier = in let real = let* x = alpha in - let* xs = zero_many (alpha <|> digit) in + let* xs = zero_many (alpha <|> digit <|> char '_') in let name = string_of_chars (x :: xs) in if reserved name then fail (SyntaxError name) else return (Ast.Real name) in diff --git a/Lazarev/lib/parser.mli b/Lazarev/lib/parser.mli index d72b4218..951720af 100644 --- a/Lazarev/lib/parser.mli +++ b/Lazarev/lib/parser.mli @@ -1,10 +1,10 @@ -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (** Type for parsing error *) type error = diff --git a/Lazarev/lib/utils.mli b/Lazarev/lib/utils.mli index 05fbc9da..edacd694 100644 --- a/Lazarev/lib/utils.mli +++ b/Lazarev/lib/utils.mli @@ -1,10 +1,10 @@ -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] (** Copyright 2021-2024, Kakadu and contributors *) (** SPDX-License-Identifier: LGPL-3.0-or-later *) -[@@@ocaml.text "*/*"] +[@@@ocaml.text "/*"] module type READER_MONAD = sig type ('s, 'a) t From 951e628183b4c31b0d5f1c59daf062a3241202ea Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 06:11:12 +0300 Subject: [PATCH 14/28] Fix unused type declaration Signed-off-by: Andrew Lazarev --- Lazarev/bin/REPL.ml | 1 - Lazarev/lib/interpreter.ml | 2 -- 2 files changed, 3 deletions(-) diff --git a/Lazarev/bin/REPL.ml b/Lazarev/bin/REPL.ml index b0d49a7c..d0c0d15a 100644 --- a/Lazarev/bin/REPL.ml +++ b/Lazarev/bin/REPL.ml @@ -7,7 +7,6 @@ [@@@ocaml.text "*/*"] module Arg = Stdlib.Arg -module Ast = Mini_ml_lib.Ast module Interpreter = Mini_ml_lib.Interpreter module Parser = Mini_ml_lib.Parser diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml index 1b5e25dc..428e36ee 100644 --- a/Lazarev/lib/interpreter.ml +++ b/Lazarev/lib/interpreter.ml @@ -33,8 +33,6 @@ and value = | Closure of Ast.t * env | BuiltinAbstraction of (value -> value result) -type variables = (Ast.name * value) list - module InterpreterState : Utils.STATE_MONAD = struct type ('s, 'a) t = 's -> 's * 'a From 22fb0a9ba9e0d72689ece2cacb0aff4dcab4a16a Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 06:26:39 +0300 Subject: [PATCH 15/28] Fix liter comments Signed-off-by: Andrew Lazarev --- Lazarev/lib/interpreter.ml | 5 ++--- Lazarev/lib/parser.ml | 6 ++---- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml index 428e36ee..a10c5806 100644 --- a/Lazarev/lib/interpreter.ml +++ b/Lazarev/lib/interpreter.ml @@ -45,7 +45,7 @@ module InterpreterState : Utils.STATE_MONAD = struct let read : ('st, 'st) t = fun state -> state, state let write : 'st -> ('st, unit) t = fun s _ -> s, () - let run func state = func state + let run func = func end let rec show_value_type = function @@ -83,8 +83,7 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct let set_vars vars = ST.bind ST.read (fun env -> ST.write (vars, snd env)) let update_limit = - ST.bind ST.read (fun st -> - match st with + ST.bind ST.read (function | _, Unlimited -> ST.return () | env, Limited n when n > 0 -> ST.write (env, Limited (n - 1)) | _, Limited _ -> ST.return ()) diff --git a/Lazarev/lib/parser.ml b/Lazarev/lib/parser.ml index 782558bb..08c08137 100644 --- a/Lazarev/lib/parser.ml +++ b/Lazarev/lib/parser.ml @@ -34,8 +34,7 @@ let ( let* ) = bind let string_of_chars chars = chars |> List.to_seq |> String.of_seq let chars_of_string string = string |> String.to_seq |> List.of_seq -let satisfy predicate chars = - match chars with +let satisfy predicate = function | h :: tl when predicate h -> return h tl | h :: tl -> fail (SyntaxError (string_of_chars (h :: tl))) tl | [] -> fail UnexpectedEnd [] @@ -102,8 +101,7 @@ let chars string = | c :: rest -> List.fold_left ( *> ) (char c) (List.map char rest) ;; -let reserved str = - match str with +let reserved = function | "let" -> true | "rec" -> true | "in" -> true From 9d079343f9a036875293a8078c1c8bdbfeb05b4a Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 06:27:49 +0300 Subject: [PATCH 16/28] Fix liter comments 2 Signed-off-by: Andrew Lazarev --- Lazarev/bin/REPL.ml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Lazarev/bin/REPL.ml b/Lazarev/bin/REPL.ml index d0c0d15a..38c5bc9c 100644 --- a/Lazarev/bin/REPL.ml +++ b/Lazarev/bin/REPL.ml @@ -56,7 +56,6 @@ let () = ] in Arg.parse args (fun _ -> ()) "An interpreter for ML-like language"; - match options.multiline with - | false -> run_one options.env - | true -> run_many options.env + let env = options.env in + if options.multiline then run_one env else run_many env ;; From ad56f25b2c0037b88d14c945f4a9ad096b7499f2 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 06:29:21 +0300 Subject: [PATCH 17/28] Fix linter comments 3 Signed-off-by: Andrew Lazarev --- Lazarev/lib/parser.ml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lazarev/lib/parser.ml b/Lazarev/lib/parser.ml index 08c08137..dc288176 100644 --- a/Lazarev/lib/parser.ml +++ b/Lazarev/lib/parser.ml @@ -272,8 +272,8 @@ let parse_line line = let show_error = function | UnexpectedEnd -> "Unexpected end of input" - | UnexpectedRest s -> Format.sprintf {|Unparsed symbols: "%s"|} s - | SyntaxError s -> Format.sprintf {|Syntax error: "%s"|} s + | UnexpectedRest s -> Format.sprintf {|Unparsed symbols: %S|} s + | SyntaxError s -> Format.sprintf {|Syntax error: %S|} s ;; let show_result = function From 84eb5c70ef941e4fef648bcbf8156eac5d9b45b4 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 06:40:50 +0300 Subject: [PATCH 18/28] Fix linter comments 4 Signed-off-by: Andrew Lazarev --- Lazarev/bin/REPL.ml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Lazarev/bin/REPL.ml b/Lazarev/bin/REPL.ml index 38c5bc9c..377f613b 100644 --- a/Lazarev/bin/REPL.ml +++ b/Lazarev/bin/REPL.ml @@ -56,6 +56,5 @@ let () = ] in Arg.parse args (fun _ -> ()) "An interpreter for ML-like language"; - let env = options.env in - if options.multiline then run_one env else run_many env + if options.multiline then run_many options.env else run_one options.env ;; From 954b515e820826bdac2da40d710ca75c9ba4e12e Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Sat, 18 Apr 2026 09:12:51 +0300 Subject: [PATCH 19/28] Fix REPL help message, Add new tests Signed-off-by: Andrew Lazarev --- Lazarev/bin/REPL.ml | 2 +- Lazarev/tests/interpreter.t | 54 ++++++++++++++++++++++++++----------- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/Lazarev/bin/REPL.ml b/Lazarev/bin/REPL.ml index 377f613b..ce1f92d7 100644 --- a/Lazarev/bin/REPL.ml +++ b/Lazarev/bin/REPL.ml @@ -49,7 +49,7 @@ let () = let args = [ ( "--steps" , Arg.Int (fun n -> options.env <- Interpreter.new_env_limited n) - , "Set maximum number of evaluation steps (default: 1000)" ) + , "Set maximum number of evaluation steps" ) ; ( "--multiline" , Arg.Unit (fun _ -> options.multiline <- true) , "Enable multiline input for read eval print loop" ) diff --git a/Lazarev/tests/interpreter.t b/Lazarev/tests/interpreter.t index 646af1e9..27b1ea93 100644 --- a/Lazarev/tests/interpreter.t +++ b/Lazarev/tests/interpreter.t @@ -13,7 +13,7 @@ Test with no input $ ../bin/REPL.exe --help < !42 Error: Type mismatch: 'int' - $ ../bin/REPL.exe --steps 1 < !(true || false && false && true) - Error: Steps limit exceeded - $ ../bin/REPL.exe < 2 > 1 <> false bool: true @@ -108,6 +104,14 @@ Test logical & compare operations > if (true <> false) then -42 else 42 int: -42 + $ ../bin/REPL.exe --steps 3 < !(true || false && false && true) + Error: Steps limit exceeded + + $ ../bin/REPL.exe < !(false || -true) + Error: Type mismatch: 'bool' + Test variables $ ../bin/REPL.exe <: ? * : ?, ? + $ ../bin/REPL.exe < (print_int true) + Error: Invalid application + $ ../bin/REPL.exe --multiline < (print_hoho 100) > ((1 + 1) 100) @@ -198,7 +206,19 @@ Test if-then-else statement > if () then true else false Error: Type mismatch: 'unit' -Test non-recursive let statement & builtin abstraction +Test non-recursive let statement & built-in abstraction + + $ ../bin/REPL.exe --steps 100000 < let letrec = 123 in let ifthen = 321 in ((letrec + ifthen), (ifthen - letrec)) + int * int: 444, 198 + + $ ../bin/REPL.exe < let x = 12000 in let y = -12000 in ((fun x y -> (x + y)) x y) + int: 0 + + $ ../bin/REPL.exe --steps 100000 < let print_int = 123 in print_int + int: 123 $ ../bin/REPL.exe < let a = 512 * 2 - 24 in (print_int a) @@ -231,34 +251,38 @@ Test non-recursive let statement & builtin abstraction > let a = 1 in a + b Error: Unbound variable 'b' + $ ../bin/REPL.exe < let rec a = 1 in let rec b = 2 in (a = b) + Error: Invalid let-statement + Test recursive let statement $ ../bin/REPL.exe < let rec sum = fun n -> if (n = 0) then 0 else (n + (sum (n - 1))) in (sum 100) + > let rec sum = fun n -> if n = 0 then 0 else (n + (sum (n - 1))) in (sum 100) int: 5050 $ ../bin/REPL.exe < let rec fact = fun n -> (if (n = 0) then 1 else (n * (fact (n - 1)))) in (fact 6) + > let rec fact = fun n -> (if n = 0 then 1 else (n * (fact (n - 1)))) in (fact 6) int: 720 $ ../bin/REPL.exe --steps 10 < let rec fact = fun n -> (if (n = 0) then 1 else (n * (fact (n - 1)))) in (fact 6) + > let rec fact = fun n -> (if n = 0 then 1 else (n * (fact (n - 1)))) in (fact 6) Error: Steps limit exceeded - $ ../bin/REPL.exe --steps 500 < let rec fact = fun n -> (if (n = 0) then 1 else (n * (fact (n - 1)))) in (fact 6) - int: 720 + $ ../bin/REPL.exe --steps 100 < let rec fact = fun n -> (if n = 0 then 1 else (n * (fact (n - 1)))) in (fact 7) + int: 5040 $ ../bin/REPL.exe < let rec fix = fun f s -> (f (fix f) s) in (fix (fun self n -> if (n <= 1) then 1 else (n * (self (n - 1)))) 7) + > let rec fix = fun f s -> (f (fix f) s) in let fac = fun n -> (fix (fun self n -> if n <= 1 then 1 else (n * (self (n - 1)))) n) in (fac 7) int: 5040 $ ../bin/REPL.exe < let rec fib = fun n -> if (n <= 2) then 1 else ((fib (n - 1)) + (fib (n - 2))) in (fib 8) + > let rec fib = fun n -> if n <= 2 then 1 else ((fib (n - 1)) + (fib (n - 2))) in (fib 8) int: 21 $ ../bin/REPL.exe < let rec fib = fun n -> if (n <= 2) then 1 else ((fib (n - 1)) + (fib (n - 2))) in (fib 20) + > let rec fib = fun n -> if n <= 2 then 1 else ((fib (n - 1)) + (fib (n - 2))) in (fib 20) int: 6765 Test some infinite recursions From 0a8a556dbd5a0d9370c0ced94d398fd89afe8a50 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Mon, 20 Apr 2026 17:22:40 +0300 Subject: [PATCH 20/28] Fix: configuration files Signed-off-by: Andrew Lazarev --- Lazarev/Lazarev.opam | 2 -- Lazarev/dune-project | 3 --- 2 files changed, 5 deletions(-) diff --git a/Lazarev/Lazarev.opam b/Lazarev/Lazarev.opam index 4f06b164..e2ce5617 100644 --- a/Lazarev/Lazarev.opam +++ b/Lazarev/Lazarev.opam @@ -11,9 +11,7 @@ doc: "https://kakadu.github.io/fp25/docs/Lambda" bug-reports: "https://github.com/Kakadu/fp25" depends: [ "dune" {>= "3.7" & = "3.19.1"} - "angstrom" {= "0.16.0"} "base" - "fix" "ppx_inline_test" {with-test} "ppx_expect" "ppx_deriving" diff --git a/Lazarev/dune-project b/Lazarev/dune-project index 1615f112..3e8e8017 100644 --- a/Lazarev/dune-project +++ b/Lazarev/dune-project @@ -23,10 +23,7 @@ (depends (dune (= "3.19.1")) - (angstrom - (= "0.16.0")) base - fix (ppx_inline_test :with-test) ppx_expect ppx_deriving From 35f59718a8d7b896eef2227629248ed2ced31405 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Mon, 20 Apr 2026 18:05:34 +0300 Subject: [PATCH 21/28] Add exceptions to AST Signed-off-by: Andrew Lazarev --- Lazarev/lib/ast.ml | 15 +++++++++++++++ Lazarev/lib/ast.mli | 3 +++ Lazarev/tests/ast_tests.ml | 25 +++++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/Lazarev/lib/ast.ml b/Lazarev/lib/ast.ml index 111581a5..aa5e3c3f 100644 --- a/Lazarev/lib/ast.ml +++ b/Lazarev/lib/ast.ml @@ -48,6 +48,9 @@ type t = | LetExpr of let_mnemonic * name * t * t | Abstraction of name * t | Application of t * t + | Exception of string + | TryWith of t * string * t + | Raise of t let show_name = function | Wildcard -> "_" @@ -88,6 +91,14 @@ let rec show_ast_verbose = function Format.sprintf "Abs(%s, %s)" (show_name name) (show_ast_verbose expr) | Application (lhs, rhs) -> Format.sprintf "App(%s, %s)" (show_ast_verbose lhs) (show_ast_verbose rhs) + | Exception name -> Format.sprintf "Exception(%s)" name + | TryWith (lhs, name, rhs) -> + Format.sprintf + "TryWith(%s, %s, %s)" + (show_ast_verbose lhs) + name + (show_ast_verbose rhs) + | Raise name -> Format.sprintf "Raise(%s)" (show_ast_verbose name) ;; let show_pretty_unary_operation = function @@ -149,4 +160,8 @@ let rec show_ast = function | Abstraction (var, expr) -> Format.sprintf "fun %s -> %s" (show_name var) (show_ast expr) | Application (lhs, rhs) -> Format.sprintf "((%s) (%s))" (show_ast lhs) (show_ast rhs) + | Exception name -> Format.sprintf "exception %s" name + | TryWith (lhs, name, rhs) -> + Format.sprintf "try (%s) with %s -> (%s)" (show_ast lhs) name (show_ast rhs) + | Raise name -> Format.sprintf "raise %s" (show_ast name) ;; diff --git a/Lazarev/lib/ast.mli b/Lazarev/lib/ast.mli index e1b66c4f..47add42b 100644 --- a/Lazarev/lib/ast.mli +++ b/Lazarev/lib/ast.mli @@ -50,6 +50,9 @@ type t = | LetExpr of let_mnemonic * name * t * t (** Let expression [let x = ... in ...] *) | Abstraction of name * t (** Lambda abstraction [fun x -> ...] *) | Application of t * t (** Application [(f x)] *) + | Exception of string (** Exception declaration [exception Division_by_zero] *) + | TryWith of t * string * t (** Try with statement [try (...) with ... -> (...)] *) + | Raise of t (** Fail with statement [raise ...] *) (** Shows AST in verbose format *) val show_ast_verbose : t -> string diff --git a/Lazarev/tests/ast_tests.ml b/Lazarev/tests/ast_tests.ml index 95a82998..17956d60 100644 --- a/Lazarev/tests/ast_tests.ml +++ b/Lazarev/tests/ast_tests.ml @@ -92,3 +92,28 @@ let%test "Applications & abstractions" = "App(App(Abs(_, Abs(a, 12)), x1), x2)" "((((fun _ -> fun a -> 12) (x1))) (x2))" ;; + +let declare_excepttion name = Ast.Exception name +let try_with left name right = Ast.TryWith (left, name, right) +let raise expr = Ast.Raise expr + +let%test "Exceptions 1" = + expect + (try_with + (app (var "print_int") (const 4242)) + "VeryBadCase" + (app (var "print_bool") (bool false))) + "TryWith(App(print_int, 4242), VeryBadCase, App(print_bool, false))" + "try (((print_int) (4242))) with VeryBadCase -> (((print_bool) (false)))" +;; + +let%test "Exceptions 2" = + expect (raise (abs (name "x") (bool true))) "Raise(Abs(x, true))" "raise fun x -> true" +;; + +let%test "Exceptions 3" = + expect + (declare_excepttion "DivisionByZero") + "Exception(DivisionByZero)" + "exception DivisionByZero" +;; From 87f605627db2c7024ef08b02451aac67b15740d2 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Mon, 20 Apr 2026 18:48:20 +0300 Subject: [PATCH 22/28] Add exceptions to parser Signed-off-by: Andrew Lazarev --- Lazarev/lib/parser.ml | 41 ++++++++++++++++++++++++++++++++++- Lazarev/tests/parser_tests.ml | 32 ++++++++++++++++++++------- 2 files changed, 64 insertions(+), 9 deletions(-) diff --git a/Lazarev/lib/parser.ml b/Lazarev/lib/parser.ml index dc288176..025bb816 100644 --- a/Lazarev/lib/parser.ml +++ b/Lazarev/lib/parser.ml @@ -82,6 +82,12 @@ let one_many parser = return (x :: xs) ;; +let capital_alpha = + satisfy (function + | 'A' .. 'Z' -> true + | _ -> false) +;; + let alpha = satisfy (function | 'a' .. 'z' -> true @@ -112,6 +118,10 @@ let reserved = function | "false" -> true | "true" -> true | "mod" -> true + | "exception" -> true + | "try" -> true + | "with" -> true + | "raise" -> true | _ -> false ;; @@ -133,6 +143,13 @@ let identifier = wildcard <|> real ;; +let exception_identifier = + let* x = capital_alpha in + let* xs = zero_many (alpha <|> digit <|> char '_') in + let name = string_of_chars (x :: xs) in + if reserved name then fail (SyntaxError name) else return name +;; + let term = let integer = let* chars = one_many digit in @@ -226,6 +243,20 @@ let atom = in let let_expr = letrec "let" Ast.Let in let let_rec_expr = letrec "let rec" Ast.LetRec in + let raise_expr parser = + let* _ = chars "raise" in + let* expr = ws1 *> parser in + return (Ast.Raise expr) + in + let trywith_expr parser1 parser2 = + let* _ = chars "try" in + let* expr1 = ws1 *> parser1 in + let* _ = ws1 *> chars "with" in + let* name = ws1 *> exception_identifier in + let* _ = ws0 *> chars "->" in + let* expr2 = ws0 *> parser2 in + return (Ast.TryWith (expr1, name, expr2)) + in fix (fun atom -> let atom_fix = fix (fun inner -> @@ -237,6 +268,8 @@ let atom = <|> if_expr atom inner <|> let_expr atom inner <|> let_rec_expr atom inner + <|> raise_expr inner + <|> trywith_expr atom inner <|> parens atom) in apply_precedence @@ -259,6 +292,12 @@ let atom = |]) ;; +let exception_decl = + let* _ = ws0 *> chars "exception" in + let* name = ws1 *> exception_identifier <* ws0 in + return (Ast.Exception name) +;; + let wrap_result = function | Parsed (a, rest) when rest = [] -> Parsed (a, rest) | Parsed (_, rest) -> ParseError (UnexpectedRest (string_of_chars rest)) @@ -267,7 +306,7 @@ let wrap_result = function let parse_line line = let expr = ws0 *> atom <* ws0 in - chars_of_string line |> expr |> wrap_result + chars_of_string line |> (expr <|> exception_decl) |> wrap_result ;; let show_error = function diff --git a/Lazarev/tests/parser_tests.ml b/Lazarev/tests/parser_tests.ml index 79959248..37f308e9 100644 --- a/Lazarev/tests/parser_tests.ml +++ b/Lazarev/tests/parser_tests.ml @@ -49,16 +49,22 @@ let%expect_test "Correct parsing" = "fun a -> -(if a then 1 else 2)" |> parse_and_print; [%expect "Abs(a, Neg(IfThenElse(a, 1, 2)))"]; "let a = 1 in let b = 2 in let c = 3 in (a + b + c)" |> parse_and_print; - [%expect "Let(a, 1, Let(b, 2, Let(c, 3, Add(Add(a, b), c))))"] + [%expect "Let(a, 1, Let(b, 2, Let(c, 3, Add(Add(a, b), c))))"]; + "exception DivisionByZero" |> parse_and_print; + [%expect "Exception(DivisionByZero)"]; + "raise 0" |> parse_and_print; + [%expect "Raise(0)"]; + "raise (if a = 0 then true else false)" |> parse_and_print; + [%expect "Raise(IfThenElse(Equal(a, 0), true, false))"] ;; (* Test if invalid expressions are not parsed *) let%expect_test "Invalid expressions" = "( )" |> parse_and_print; - [%expect {|Syntax error: ")"|}]; + [%expect {|Syntax error: "( )"|}]; "(1 $ 2" |> parse_and_print; - [%expect {|Syntax error: "$ 2"|}]; + [%expect {|Syntax error: "(1 $ 2"|}]; "var & mask)" |> parse_and_print; [%expect {|Unparsed symbols: "& mask)"|}]; "var += 1" |> parse_and_print; @@ -66,11 +72,11 @@ let%expect_test "Invalid expressions" = "(567 / 3) + (567 % 3" |> parse_and_print; [%expect {|Unparsed symbols: "+ (567 % 3"|}]; "(call 1invalid2identifier)" |> parse_and_print; - [%expect {|Syntax error: "1invalid2identifier)"|}]; + [%expect {|Syntax error: "(call 1invalid2identifier)"|}]; "+ 1 2 3" |> parse_and_print; [%expect {|Syntax error: "+ 1 2 3"|}]; "(1, 2, 3 helloWorld)" |> parse_and_print; - [%expect {|Syntax error: ", 2, 3 helloWorld)"|}]; + [%expect {|Syntax error: "(1, 2, 3 helloWorld)"|}]; "fun x y ->" |> parse_and_print; [%expect {|Syntax error: "fun x y ->"|}]; "if a <> 0 then 1" |> parse_and_print; @@ -84,11 +90,15 @@ let%expect_test "Invalid expressions" = "let true = 1 in false" |> parse_and_print; [%expect {|Syntax error: "let true = 1 in false"|}]; "(1, 2, (if, then))" |> parse_and_print; - [%expect {|Syntax error: ", 2, (if, then))"|}]; + [%expect {|Syntax error: "(1, 2, (if, then))"|}]; "(then, 3)" |> parse_and_print; - [%expect {|Syntax error: "then, 3)"|}]; + [%expect {|Syntax error: "(then, 3)"|}]; "let var = 1" |> parse_and_print; - [%expect {|Syntax error: "let var = 1"|}] + [%expect {|Syntax error: "let var = 1"|}]; + "exception" |> parse_and_print; + [%expect {|Unexpected end of input|}]; + "exception if" |> parse_and_print; + [%expect {|Syntax error: "if"|}] ;; let same lhs rhs = @@ -217,6 +227,12 @@ let gen_ast_depth = gen_any_name sub_small sub ) + ; ( 1 + , map2 + (fun expr1 expr2 -> Ast.TryWith (expr1, "Exception", expr2)) + sub + sub_small ) + ; 1, map (fun expr -> Ast.Raise expr) sub ])) ;; From 3aad835f48e67797de48f78715fc0b4f4b79f6f5 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Mon, 20 Apr 2026 20:39:49 +0300 Subject: [PATCH 23/28] Add exceptions to Interpreter Signed-off-by: Andrew Lazarev --- Lazarev/lib/interpreter.ml | 65 ++++++++++++++++++++++++--------- Lazarev/lib/interpreter.mli | 4 +-- Lazarev/tests/interpreter.t | 72 ++++++++++++++++++++++++++----------- 3 files changed, 101 insertions(+), 40 deletions(-) diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml index a10c5806..e48764f8 100644 --- a/Lazarev/lib/interpreter.ml +++ b/Lazarev/lib/interpreter.ml @@ -7,8 +7,6 @@ [@@@ocaml.text "/*"] type error = - | LimitError - | ZeroDivision | InvalidApplication | InvalidLet | UnboundVariable of Ast.name @@ -17,6 +15,7 @@ type error = type 'a result = | Eval of 'a + | EvalRaise of string | EvalError of error type step_limit = @@ -30,10 +29,11 @@ and value = | Int of int | Bool of bool | Tuple of value * value * value list + | Exception of string | Closure of Ast.t * env | BuiltinAbstraction of (value -> value result) -module InterpreterState : Utils.STATE_MONAD = struct +module State : Utils.STATE_MONAD = struct type ('s, 'a) t = 's -> 's * 'a let return x st = st, x @@ -53,13 +53,15 @@ let rec show_value_type = function | Int _ -> "int" | Bool _ -> "bool" | Tuple (t1, t2, ts) -> String.concat " * " (List.map show_value_type (t1 :: t2 :: ts)) + | Exception _ -> "exception" | Closure _ -> "" | BuiltinAbstraction _ -> "" ;; -module Interpreter (ST : Utils.STATE_MONAD) = struct +module Result (ST : Utils.STATE_MONAD) = struct let return x = ST.return (Eval x) let fail e = ST.return (EvalError e) + let raise e = ST.return (EvalRaise e) (* Two different bind operators here *) (* '>>=' is used for State *) @@ -70,6 +72,7 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct let ( let* ) x transform = ST.bind x (function | Eval x -> transform x + | EvalRaise e -> raise e | EvalError e -> fail e) ;; @@ -81,6 +84,7 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct ;; let set_vars vars = ST.bind ST.read (fun env -> ST.write (vars, snd env)) + let set_limit limit = ST.bind ST.read (fun env -> ST.write (fst env, limit)) let update_limit = ST.bind ST.read (function @@ -102,9 +106,9 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct | Ast.Add, Int l, Int r -> return (Int (l + r)) | Ast.Sub, Int l, Int r -> return (Int (l - r)) | Ast.Mul, Int l, Int r -> return (Int (l * r)) - | Ast.Div, Int _, Int r when r = 0 -> fail ZeroDivision + | Ast.Div, Int _, Int r when r = 0 -> raise "DivisionByZero" | Ast.Div, Int l, Int r -> return (Int (l / r)) - | Ast.Mod, Int _, Int r when r = 0 -> fail ZeroDivision + | Ast.Mod, Int _, Int r when r = 0 -> raise "DivisionByZero" | Ast.Mod, Int l, Int r -> return (Int (l mod r)) | Ast.And, Bool l, Bool r -> return (Bool (l && r)) | Ast.Or, Bool l, Bool r -> return (Bool (l || r)) @@ -133,7 +137,7 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct let* _ = get_limit >>= function - | Limited 0 -> fail LimitError + | Limited 0 -> raise "StepsOverflow" | _ -> return () in let* _ = update_limit >>= fun _ -> return () in @@ -195,9 +199,9 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct | Ast.Abstraction _ as abs -> get_limit >>= fun limit -> get_vars >>= fun vars -> return (Closure (abs, (vars, limit))) - | Ast.Application (expr1, expr2) -> - let* v1 = eval expr1 in - let* v2 = eval expr2 in + | Ast.Application (e1, e2) -> + let* v1 = eval e1 in + let* v2 = eval e2 in (match v1 with | Closure (Ast.Abstraction (arg, expr), env) -> get_vars @@ -209,8 +213,35 @@ module Interpreter (ST : Utils.STATE_MONAD) = struct | BuiltinAbstraction f -> (match f v2 with | Eval v -> return v + | EvalRaise e -> raise e | EvalError e -> fail e) | _ -> fail InvalidApplication) + | Ast.Exception name -> + let v = Exception name in + update_vars (Ast.Real name) v >>= fun _ -> return v + | Ast.Raise expr -> + get_vars + >>= fun vars -> + let* v = eval expr in + (match v with + | Exception name as e when lookup (Ast.Real name) vars = Some e -> raise name + | _ -> fail (TypesMismatch ("exception", show_value_type v))) + | Ast.TryWith (e1, name, e2) -> + get_limit + >>= fun saved_limit -> + get_vars + >>= fun saved_vars -> + ST.bind (eval e1) (function + | Eval x -> return x + | EvalRaise name' when String.equal name' name -> + set_limit saved_limit + >>= fun _ -> + set_vars saved_vars + >>= fun _ -> + let* v2 = eval e2 in + return v2 + | EvalRaise name -> raise name + | EvalError error -> fail error) ;; end @@ -255,13 +286,11 @@ let new_env = get_builtins, Unlimited let new_env_limited limit = get_builtins, Limited limit let show_error = function - | LimitError -> "Steps limit exceeded" - | ZeroDivision -> "Division by zero" | InvalidApplication -> "Invalid application" | InvalidLet -> "Invalid let-statement" - | UnboundVariable name -> Format.sprintf "Unbound variable '%s'" (Ast.show_name name) - | TypeMismatch typ -> Format.sprintf "Type mismatch: '%s'" typ - | TypesMismatch (typ1, typ2) -> Format.sprintf "Types mismatch: '%s' and '%s'" typ1 typ2 + | UnboundVariable name -> Format.sprintf "Unbound variable %S" (Ast.show_name name) + | TypeMismatch typ -> Format.sprintf "Type mismatch: %S" typ + | TypesMismatch (typ1, typ2) -> Format.sprintf "Types mismatch: %S and %S" typ1 typ2 ;; let show_result result = @@ -270,14 +299,16 @@ let show_result result = | Int int -> string_of_int int | Bool bool -> string_of_bool bool | Tuple (v1, v2, vs) -> String.concat ", " (List.map show_eval (v1 :: v2 :: vs)) + | Exception name -> name | Closure _ | BuiltinAbstraction _ -> "?" in match result with | Eval value -> Format.sprintf "%s: %s" (show_value_type value) (show_eval value) + | EvalRaise exception_name -> Format.sprintf "Raised: %S" exception_name | EvalError error -> Format.sprintf "Error: %s" (show_error error) ;; let run env expr = - let module I = Interpreter (InterpreterState) in - InterpreterState.run (I.eval expr) env + let module R = Result (State) in + State.run (R.eval expr) env ;; diff --git a/Lazarev/lib/interpreter.mli b/Lazarev/lib/interpreter.mli index 5ada1a6c..cbe64873 100644 --- a/Lazarev/lib/interpreter.mli +++ b/Lazarev/lib/interpreter.mli @@ -8,8 +8,6 @@ (** Type for interpreter's error *) type error = - | LimitError (** When step limit is reached *) - | ZeroDivision (** When divider has been evaluated to zero *) | InvalidApplication (** When application is not valid *) | InvalidLet (** When recursive let statement is used wrongly *) | UnboundVariable of Ast.name (** When provided name is not a variable *) @@ -19,6 +17,7 @@ type error = (** Type for evaluation result *) type 'a result = | Eval of 'a + | EvalRaise of string | EvalError of error (** Type for step limit *) @@ -32,6 +31,7 @@ type value = | Int of int | Bool of bool | Tuple of value * value * value list + | Exception of string | Closure of Ast.t * env | BuiltinAbstraction of (value -> value result) diff --git a/Lazarev/tests/interpreter.t b/Lazarev/tests/interpreter.t index 27b1ea93..4c3837b3 100644 --- a/Lazarev/tests/interpreter.t +++ b/Lazarev/tests/interpreter.t @@ -56,19 +56,19 @@ Test arithmetic operations $ ../bin/REPL.exe < 11 / (2 + 2 - (8 / 2)) + 1 - Error: Division by zero + Raised: "DivisionByZero" $ ../bin/REPL.exe < (42) mod (0) - Error: Division by zero + Raised: "DivisionByZero" $ ../bin/REPL.exe --steps 3 < 1 + 2 + 3 + 4 + 5 - Error: Steps limit exceeded + Raised: "StepsOverflow" $ ../bin/REPL.exe < ((1) / (true)) - Error: Types mismatch: 'int' and 'bool' + Error: Types mismatch: "int" and "bool" Test logical & compare operations @@ -82,7 +82,7 @@ Test logical & compare operations $ ../bin/REPL.exe < !42 - Error: Type mismatch: 'int' + Error: Type mismatch: "int" $ ../bin/REPL.exe < 2 > 1 <> false @@ -106,17 +106,17 @@ Test logical & compare operations $ ../bin/REPL.exe --steps 3 < !(true || false && false && true) - Error: Steps limit exceeded + Raised: "StepsOverflow" $ ../bin/REPL.exe < !(false || -true) - Error: Type mismatch: 'bool' + Error: Type mismatch: "bool" Test variables $ ../bin/REPL.exe < a + b - Error: Unbound variable 'a' + Error: Unbound variable "a" Test abstraction & application @@ -138,7 +138,7 @@ Test abstraction & application $ ../bin/REPL.exe < ((fun x -> x) _) - Error: Unbound variable '_' + Error: Unbound variable "_" $ ../bin/REPL.exe --multiline < (print_int 100) @@ -163,7 +163,7 @@ Test abstraction & application $ ../bin/REPL.exe --multiline < (print_hoho 100) > ((1 + 1) 100) - Error: Unbound variable 'print_hoho' + Error: Unbound variable "print_hoho" Error: Invalid application Test tuples of different types @@ -186,7 +186,7 @@ Test tuples of different types $ ../bin/REPL.exe < ((5 mod 2), false) * (1, 2) - Error: Types mismatch: 'int * bool' and 'int * int' + Error: Types mismatch: "int * bool" and "int * int" Test if-then-else statement @@ -200,11 +200,11 @@ Test if-then-else statement $ ../bin/REPL.exe < if (1 + 2) then (print_int 1) else 42 - Error: Type mismatch: 'int' + Error: Type mismatch: "int" $ ../bin/REPL.exe < if () then true else false - Error: Type mismatch: 'unit' + Error: Type mismatch: "unit" Test non-recursive let statement & built-in abstraction @@ -249,7 +249,7 @@ Test non-recursive let statement & built-in abstraction $ ../bin/REPL.exe < let a = 1 in a + b - Error: Unbound variable 'b' + Error: Unbound variable "b" $ ../bin/REPL.exe < let rec a = 1 in let rec b = 2 in (a = b) @@ -267,7 +267,7 @@ Test recursive let statement $ ../bin/REPL.exe --steps 10 < let rec fact = fun n -> (if n = 0 then 1 else (n * (fact (n - 1)))) in (fact 6) - Error: Steps limit exceeded + Raised: "StepsOverflow" $ ../bin/REPL.exe --steps 100 < let rec fact = fun n -> (if n = 0 then 1 else (n * (fact (n - 1)))) in (fact 7) @@ -285,20 +285,50 @@ Test recursive let statement > let rec fib = fun n -> if n <= 2 then 1 else ((fib (n - 1)) + (fib (n - 2))) in (fib 20) int: 6765 -Test some infinite recursions +Test exceptions + + $ ../bin/REPL.exe --multiline < exception DivisionByZero + > raise DivisionByZero + exception: DivisionByZero + Raised: "DivisionByZero" + + $ ../bin/REPL.exe --multiline < raise Undefined + Error: Unbound variable "Undefined" + + $ ../bin/REPL.exe --multiline < raise 42 + Error: Types mismatch: "exception" and "int" + + $ ../bin/REPL.exe --multiline < exception E1 + > try (raise E1) with E1 -> 42 + exception: E1 + int: 42 + +Test some infinite recursions and exceptions $ ../bin/REPL.exe --steps 1000 < let rec hehe = (fun _ -> (1 + (hehe 1))) in (hehe 1) - Error: Steps limit exceeded + Raised: "StepsOverflow" $ ../bin/REPL.exe --steps 100 < let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega - Error: Steps limit exceeded + Raised: "StepsOverflow" $ ../bin/REPL.exe --steps 1000 < let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega - Error: Steps limit exceeded + Raised: "StepsOverflow" - $ ../bin/REPL.exe --steps 100000 < let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega - Error: Steps limit exceeded + Raised: "StepsOverflow" + + $ ../bin/REPL.exe --steps 100 < try (let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega) with StepsOverflow -> 0 + int: 0 + + $ ../bin/REPL.exe --steps 100 < try (let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega) with StepsOverflow -> try (let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega) with StepsOverflow -> 1 + int: 1 From 0e93667506d6d95b6274d69e28bcb6b9ab7808d4 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Mon, 20 Apr 2026 22:05:38 +0300 Subject: [PATCH 24/28] Add qcheck dep. to project file Signed-off-by: Andrew Lazarev --- Lazarev/dune-project | 1 + 1 file changed, 1 insertion(+) diff --git a/Lazarev/dune-project b/Lazarev/dune-project index 3e8e8017..0430dd95 100644 --- a/Lazarev/dune-project +++ b/Lazarev/dune-project @@ -23,6 +23,7 @@ (depends (dune (= "3.19.1")) + qcheck base (ppx_inline_test :with-test) ppx_expect From b7b77b3f4618b12f2a59d85740669497ff7c6fb7 Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Mon, 20 Apr 2026 22:17:37 +0300 Subject: [PATCH 25/28] Removed weird tests Signed-off-by: Andrew Lazarev --- Lazarev/tests/parser_tests.ml | 28 +--------------------------- 1 file changed, 1 insertion(+), 27 deletions(-) diff --git a/Lazarev/tests/parser_tests.ml b/Lazarev/tests/parser_tests.ml index 37f308e9..5cde2f8f 100644 --- a/Lazarev/tests/parser_tests.ml +++ b/Lazarev/tests/parser_tests.ml @@ -262,38 +262,12 @@ let roundtrip_test_2 = | ParseError _ -> false) ;; -let parser_idempotent_test = - Test.make - ~name:"Parser idempotence" - ~count:20 - (make ~print:Fun.id gen_expr) - (fun expr -> - let ast1 = Parser.parse_line expr in - let ast2 = Parser.parse_line expr in - ast1 = ast2) -;; - -let printer_idempotent_test = - Test.make - ~name:"Printer idempotence" - ~count:20 - (make ~print:Ast.show_ast (gen_ast 10)) - (fun ast -> - let string1 = Ast.show_ast ast in - let string2 = Ast.show_ast ast in - string1 = string2) -;; - let%test "QCheck test" = let res = QCheck_runner.run_tests ~long:true ~verbose:true - [ roundtrip_test_1 - ; roundtrip_test_2 - ; parser_idempotent_test - ; printer_idempotent_test - ] + [ roundtrip_test_1; roundtrip_test_2 ] in res = 0 ;; From 4d8a2f7833ca6a06883ef4294b3fe835a445aa4d Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Tue, 21 Apr 2026 10:28:30 +0300 Subject: [PATCH 26/28] Minor fixes in library Signed-off-by: Andrew Lazarev --- Lazarev/lib/interpreter.ml | 32 ++++++++++++++++---------------- Lazarev/lib/parser.ml | 4 ++-- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml index e48764f8..eed052a0 100644 --- a/Lazarev/lib/interpreter.ml +++ b/Lazarev/lib/interpreter.ml @@ -58,39 +58,39 @@ let rec show_value_type = function | BuiltinAbstraction _ -> "" ;; -module Result (ST : Utils.STATE_MONAD) = struct - let return x = ST.return (Eval x) - let fail e = ST.return (EvalError e) - let raise e = ST.return (EvalRaise e) +module Result (S : Utils.STATE_MONAD) = struct + let return x = S.return (Eval x) + let fail e = S.return (EvalError e) + let raise e = S.return (EvalRaise e) (* Two different bind operators here *) (* '>>=' is used for State *) (* 'let*' is used for Eval *) - let ( >>= ) = ST.bind + let ( >>= ) = S.bind let ( let* ) x transform = - ST.bind x (function + S.bind x (function | Eval x -> transform x | EvalRaise e -> raise e | EvalError e -> fail e) ;; - let get_vars = ST.bind ST.read (fun env -> ST.return (fst env)) - let get_limit = ST.bind ST.read (fun env -> ST.return (snd env)) + let get_vars = S.bind S.read (fun env -> S.return (fst env)) + let get_limit = S.bind S.read (fun env -> S.return (snd env)) let update_vars var value = - ST.bind ST.read (fun (vars, limit) -> ST.write ((var, value) :: vars, limit)) + S.bind S.read (fun (vars, limit) -> S.write ((var, value) :: vars, limit)) ;; - let set_vars vars = ST.bind ST.read (fun env -> ST.write (vars, snd env)) - let set_limit limit = ST.bind ST.read (fun env -> ST.write (fst env, limit)) + let set_vars vars = S.bind S.read (fun env -> S.write (vars, snd env)) + let set_limit limit = S.bind S.read (fun env -> S.write (fst env, limit)) let update_limit = - ST.bind ST.read (function - | _, Unlimited -> ST.return () - | env, Limited n when n > 0 -> ST.write (env, Limited (n - 1)) - | _, Limited _ -> ST.return ()) + S.bind S.read (function + | _, Unlimited -> S.return () + | env, Limited n when n > 0 -> S.write (env, Limited (n - 1)) + | _, Limited _ -> S.return ()) ;; let eval_unop operator expr = @@ -231,7 +231,7 @@ module Result (ST : Utils.STATE_MONAD) = struct >>= fun saved_limit -> get_vars >>= fun saved_vars -> - ST.bind (eval e1) (function + S.bind (eval e1) (function | Eval x -> return x | EvalRaise name' when String.equal name' name -> set_limit saved_limit diff --git a/Lazarev/lib/parser.ml b/Lazarev/lib/parser.ml index 025bb816..9dec77d9 100644 --- a/Lazarev/lib/parser.ml +++ b/Lazarev/lib/parser.ml @@ -156,8 +156,8 @@ let term = return (Ast.Int (int_of_string (string_of_chars chars))) in let boolean = - let parser_true = chars "false" >>| fun _ -> Ast.Bool false in - let parser_false = chars "true" >>| fun _ -> Ast.Bool true in + let parser_true = chars "true" >>| fun _ -> Ast.Bool true in + let parser_false = chars "false" >>| fun _ -> Ast.Bool false in parser_true <|> parser_false in let variable = From 447192e0c881139cb02f1ee943689aa29bbc0add Mon Sep 17 00:00:00 2001 From: Andrew Lazarev Date: Tue, 21 Apr 2026 10:28:50 +0300 Subject: [PATCH 27/28] Fix: REPL is *loop* now Signed-off-by: Andrew Lazarev --- Lazarev/bin/REPL.ml | 52 +++++++++++-------------------------- Lazarev/tests/interpreter.t | 35 ++++++++----------------- 2 files changed, 26 insertions(+), 61 deletions(-) diff --git a/Lazarev/bin/REPL.ml b/Lazarev/bin/REPL.ml index ce1f92d7..dd8a9b94 100644 --- a/Lazarev/bin/REPL.ml +++ b/Lazarev/bin/REPL.ml @@ -10,51 +10,29 @@ module Arg = Stdlib.Arg module Interpreter = Mini_ml_lib.Interpreter module Parser = Mini_ml_lib.Parser -type opts = - { mutable env : Interpreter.env - ; mutable multiline : bool - } - -let get_input () = - try Some (read_line ()) with - | End_of_file -> None -;; - -let run_one env = - let line = get_input () in - match line with - | None -> print_endline "No input" - | Some input -> - (match Parser.parse_line input with - | Parser.ParseError error -> Parser.show_error error |> print_endline - | Parser.Parsed (ast, _) -> - Interpreter.run env ast |> snd |> Interpreter.show_result |> print_endline) -;; - -let rec run_many env = - let line = get_input () in - match line with - | None -> () - | Some input -> - (match Parser.parse_line input with - | Parser.ParseError error -> Parser.show_error error |> print_endline - | Parser.Parsed (ast, _) -> - let eval = Interpreter.run env ast in - eval |> snd |> Interpreter.show_result |> print_endline; - eval |> fst |> run_many) +type opts = { mutable env : Interpreter.env } + +let run env = + while true do + try + let line = read_line () in + match Parser.parse_line line with + | Parser.ParseError error -> Parser.show_error error |> print_endline + | Parser.Parsed (ast, _) -> + Interpreter.run env ast |> snd |> Interpreter.show_result |> print_endline + with + | End_of_file -> exit 0 + done ;; let () = - let options = { env = Interpreter.new_env; multiline = false } in + let options = { env = Interpreter.new_env } in let args = [ ( "--steps" , Arg.Int (fun n -> options.env <- Interpreter.new_env_limited n) , "Set maximum number of evaluation steps" ) - ; ( "--multiline" - , Arg.Unit (fun _ -> options.multiline <- true) - , "Enable multiline input for read eval print loop" ) ] in Arg.parse args (fun _ -> ()) "An interpreter for ML-like language"; - if options.multiline then run_many options.env else run_one options.env + run options.env ;; diff --git a/Lazarev/tests/interpreter.t b/Lazarev/tests/interpreter.t index 4c3837b3..935d8b28 100644 --- a/Lazarev/tests/interpreter.t +++ b/Lazarev/tests/interpreter.t @@ -14,15 +14,14 @@ Test with no input $ ../bin/REPL.exe --help < ((fun x -> x) _) Error: Unbound variable "_" - $ ../bin/REPL.exe --multiline < (print_int 100) > (print_bool false) 100 @@ -148,7 +147,7 @@ Test abstraction & application false unit: () - $ ../bin/REPL.exe --multiline < print_int > print_bool > (fst, snd) @@ -160,7 +159,7 @@ Test abstraction & application > (print_int true) Error: Invalid application - $ ../bin/REPL.exe --multiline < (print_hoho 100) > ((1 + 1) 100) Error: Unbound variable "print_hoho" @@ -225,7 +224,7 @@ Test non-recursive let statement & built-in abstraction 1000 unit: () - $ ../bin/REPL.exe --multiline < let a = let _ = (print_int 10) in 1 in let b = (print_bool true) in (a, b) > let a = let _ = (print_bool false) in false in let b = let _ = (print_int 111) in 111 in (a, b) 10 @@ -287,26 +286,14 @@ Test recursive let statement Test exceptions - $ ../bin/REPL.exe --multiline < exception DivisionByZero - > raise DivisionByZero - exception: DivisionByZero - Raised: "DivisionByZero" - - $ ../bin/REPL.exe --multiline < raise Undefined Error: Unbound variable "Undefined" - $ ../bin/REPL.exe --multiline < raise 42 Error: Types mismatch: "exception" and "int" - $ ../bin/REPL.exe --multiline < exception E1 - > try (raise E1) with E1 -> 42 - exception: E1 - int: 42 - Test some infinite recursions and exceptions $ ../bin/REPL.exe --steps 1000 < Date: Tue, 21 Apr 2026 10:53:42 +0300 Subject: [PATCH 28/28] Add 'let exception ...' construction Signed-off-by: Andrew Lazarev --- Lazarev/lib/ast.ml | 7 +++--- Lazarev/lib/ast.mli | 2 +- Lazarev/lib/interpreter.ml | 7 ++++-- Lazarev/lib/parser.ml | 16 ++++++------ Lazarev/tests/ast_tests.ml | 8 ------ Lazarev/tests/interpreter.t | 8 ++++-- Lazarev/tests/parser_tests.ml | 46 ++++++++++++----------------------- 7 files changed, 40 insertions(+), 54 deletions(-) diff --git a/Lazarev/lib/ast.ml b/Lazarev/lib/ast.ml index aa5e3c3f..e80d7c2a 100644 --- a/Lazarev/lib/ast.ml +++ b/Lazarev/lib/ast.ml @@ -48,7 +48,7 @@ type t = | LetExpr of let_mnemonic * name * t * t | Abstraction of name * t | Application of t * t - | Exception of string + | Exception of string * t | TryWith of t * string * t | Raise of t @@ -91,7 +91,8 @@ let rec show_ast_verbose = function Format.sprintf "Abs(%s, %s)" (show_name name) (show_ast_verbose expr) | Application (lhs, rhs) -> Format.sprintf "App(%s, %s)" (show_ast_verbose lhs) (show_ast_verbose rhs) - | Exception name -> Format.sprintf "Exception(%s)" name + | Exception (name, expr) -> + Format.sprintf "Exception(%s, %s)" name (show_ast_verbose expr) | TryWith (lhs, name, rhs) -> Format.sprintf "TryWith(%s, %s, %s)" @@ -160,7 +161,7 @@ let rec show_ast = function | Abstraction (var, expr) -> Format.sprintf "fun %s -> %s" (show_name var) (show_ast expr) | Application (lhs, rhs) -> Format.sprintf "((%s) (%s))" (show_ast lhs) (show_ast rhs) - | Exception name -> Format.sprintf "exception %s" name + | Exception (name, expr) -> Format.sprintf "let exception %s in %s" name (show_ast expr) | TryWith (lhs, name, rhs) -> Format.sprintf "try (%s) with %s -> (%s)" (show_ast lhs) name (show_ast rhs) | Raise name -> Format.sprintf "raise %s" (show_ast name) diff --git a/Lazarev/lib/ast.mli b/Lazarev/lib/ast.mli index 47add42b..07166796 100644 --- a/Lazarev/lib/ast.mli +++ b/Lazarev/lib/ast.mli @@ -50,7 +50,7 @@ type t = | LetExpr of let_mnemonic * name * t * t (** Let expression [let x = ... in ...] *) | Abstraction of name * t (** Lambda abstraction [fun x -> ...] *) | Application of t * t (** Application [(f x)] *) - | Exception of string (** Exception declaration [exception Division_by_zero] *) + | Exception of string * t (** Exception declaration [let exception E1 in ...] *) | TryWith of t * string * t (** Try with statement [try (...) with ... -> (...)] *) | Raise of t (** Fail with statement [raise ...] *) diff --git a/Lazarev/lib/interpreter.ml b/Lazarev/lib/interpreter.ml index eed052a0..ef6f18b7 100644 --- a/Lazarev/lib/interpreter.ml +++ b/Lazarev/lib/interpreter.ml @@ -216,9 +216,12 @@ module Result (S : Utils.STATE_MONAD) = struct | EvalRaise e -> raise e | EvalError e -> fail e) | _ -> fail InvalidApplication) - | Ast.Exception name -> + | Ast.Exception (name, expr) -> let v = Exception name in - update_vars (Ast.Real name) v >>= fun _ -> return v + update_vars (Ast.Real name) v + >>= fun _ -> + let* v = eval expr in + return v | Ast.Raise expr -> get_vars >>= fun vars -> diff --git a/Lazarev/lib/parser.ml b/Lazarev/lib/parser.ml index 9dec77d9..f6891918 100644 --- a/Lazarev/lib/parser.ml +++ b/Lazarev/lib/parser.ml @@ -243,6 +243,13 @@ let atom = in let let_expr = letrec "let" Ast.Let in let let_rec_expr = letrec "let rec" Ast.LetRec in + let let_exception parser = + let* _ = ws0 *> chars "let exception" in + let* name = ws1 *> exception_identifier in + let* _ = ws1 *> chars "in" in + let* expr = ws1 *> parser in + return (Ast.Exception (name, expr)) + in let raise_expr parser = let* _ = chars "raise" in let* expr = ws1 *> parser in @@ -268,6 +275,7 @@ let atom = <|> if_expr atom inner <|> let_expr atom inner <|> let_rec_expr atom inner + <|> let_exception inner <|> raise_expr inner <|> trywith_expr atom inner <|> parens atom) @@ -292,12 +300,6 @@ let atom = |]) ;; -let exception_decl = - let* _ = ws0 *> chars "exception" in - let* name = ws1 *> exception_identifier <* ws0 in - return (Ast.Exception name) -;; - let wrap_result = function | Parsed (a, rest) when rest = [] -> Parsed (a, rest) | Parsed (_, rest) -> ParseError (UnexpectedRest (string_of_chars rest)) @@ -306,7 +308,7 @@ let wrap_result = function let parse_line line = let expr = ws0 *> atom <* ws0 in - chars_of_string line |> (expr <|> exception_decl) |> wrap_result + chars_of_string line |> expr |> wrap_result ;; let show_error = function diff --git a/Lazarev/tests/ast_tests.ml b/Lazarev/tests/ast_tests.ml index 17956d60..b5ed9524 100644 --- a/Lazarev/tests/ast_tests.ml +++ b/Lazarev/tests/ast_tests.ml @@ -93,7 +93,6 @@ let%test "Applications & abstractions" = "((((fun _ -> fun a -> 12) (x1))) (x2))" ;; -let declare_excepttion name = Ast.Exception name let try_with left name right = Ast.TryWith (left, name, right) let raise expr = Ast.Raise expr @@ -110,10 +109,3 @@ let%test "Exceptions 1" = let%test "Exceptions 2" = expect (raise (abs (name "x") (bool true))) "Raise(Abs(x, true))" "raise fun x -> true" ;; - -let%test "Exceptions 3" = - expect - (declare_excepttion "DivisionByZero") - "Exception(DivisionByZero)" - "exception DivisionByZero" -;; diff --git a/Lazarev/tests/interpreter.t b/Lazarev/tests/interpreter.t index 935d8b28..12c989c6 100644 --- a/Lazarev/tests/interpreter.t +++ b/Lazarev/tests/interpreter.t @@ -290,6 +290,10 @@ Test exceptions > raise Undefined Error: Unbound variable "Undefined" + $ ../bin/REPL.exe < let exception E1 in 12 + int: 12 + $ ../bin/REPL.exe < raise 42 Error: Types mismatch: "exception" and "int" @@ -313,8 +317,8 @@ Test some infinite recursions and exceptions Raised: "StepsOverflow" $ ../bin/REPL.exe --steps 100 < try (let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega) with StepsOverflow -> 0 - int: 0 + > let exception HeHe in try (let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega) with StepsOverflow -> raise HeHe + Raised: "HeHe" $ ../bin/REPL.exe --steps 100 < try (let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega) with StepsOverflow -> try (let omega = ((fun x -> (x x)) (fun x -> (x x))) in omega) with StepsOverflow -> 1 diff --git a/Lazarev/tests/parser_tests.ml b/Lazarev/tests/parser_tests.ml index 5cde2f8f..8c011fb9 100644 --- a/Lazarev/tests/parser_tests.ml +++ b/Lazarev/tests/parser_tests.ml @@ -50,8 +50,8 @@ let%expect_test "Correct parsing" = [%expect "Abs(a, Neg(IfThenElse(a, 1, 2)))"]; "let a = 1 in let b = 2 in let c = 3 in (a + b + c)" |> parse_and_print; [%expect "Let(a, 1, Let(b, 2, Let(c, 3, Add(Add(a, b), c))))"]; - "exception DivisionByZero" |> parse_and_print; - [%expect "Exception(DivisionByZero)"]; + "let exception DivisionByZero in (1 + 2)" |> parse_and_print; + [%expect "Exception(DivisionByZero, Add(1, 2))"]; "raise 0" |> parse_and_print; [%expect "Raise(0)"]; "raise (if a = 0 then true else false)" |> parse_and_print; @@ -62,9 +62,9 @@ let%expect_test "Correct parsing" = let%expect_test "Invalid expressions" = "( )" |> parse_and_print; - [%expect {|Syntax error: "( )"|}]; + [%expect {|Syntax error: ")"|}]; "(1 $ 2" |> parse_and_print; - [%expect {|Syntax error: "(1 $ 2"|}]; + [%expect {|Syntax error: "$ 2"|}]; "var & mask)" |> parse_and_print; [%expect {|Unparsed symbols: "& mask)"|}]; "var += 1" |> parse_and_print; @@ -72,11 +72,11 @@ let%expect_test "Invalid expressions" = "(567 / 3) + (567 % 3" |> parse_and_print; [%expect {|Unparsed symbols: "+ (567 % 3"|}]; "(call 1invalid2identifier)" |> parse_and_print; - [%expect {|Syntax error: "(call 1invalid2identifier)"|}]; + [%expect {|Syntax error: "1invalid2identifier)"|}]; "+ 1 2 3" |> parse_and_print; [%expect {|Syntax error: "+ 1 2 3"|}]; "(1, 2, 3 helloWorld)" |> parse_and_print; - [%expect {|Syntax error: "(1, 2, 3 helloWorld)"|}]; + [%expect {|Syntax error: ", 2, 3 helloWorld)"|}]; "fun x y ->" |> parse_and_print; [%expect {|Syntax error: "fun x y ->"|}]; "if a <> 0 then 1" |> parse_and_print; @@ -90,15 +90,15 @@ let%expect_test "Invalid expressions" = "let true = 1 in false" |> parse_and_print; [%expect {|Syntax error: "let true = 1 in false"|}]; "(1, 2, (if, then))" |> parse_and_print; - [%expect {|Syntax error: "(1, 2, (if, then))"|}]; + [%expect {|Syntax error: ", 2, (if, then))"|}]; "(then, 3)" |> parse_and_print; - [%expect {|Syntax error: "(then, 3)"|}]; + [%expect {|Syntax error: "then, 3)"|}]; "let var = 1" |> parse_and_print; [%expect {|Syntax error: "let var = 1"|}]; "exception" |> parse_and_print; - [%expect {|Unexpected end of input|}]; + [%expect {|Syntax error: "exception"|}]; "exception if" |> parse_and_print; - [%expect {|Syntax error: "if"|}] + [%expect {|Syntax error: "exception if"|}] ;; let same lhs rhs = @@ -233,17 +233,17 @@ let gen_ast_depth = sub sub_small ) ; 1, map (fun expr -> Ast.Raise expr) sub + ; 1, map (fun expr -> Ast.Exception ("Exception", expr)) sub ])) ;; let gen_ast limit = Gen.sized (fun size -> gen_ast_depth (min size limit)) -let gen_expr = Gen.map Ast.show_ast (gen_ast 5) -let roundtrip_test_1 = +let roundtrip_test = Test.make ~name:"Parser round-trip 1" - ~count:50 - (make ~print:Ast.show_ast (gen_ast 7)) + ~count:100 + (make ~print:Ast.show_ast (gen_ast 8)) (fun ast -> let string = Ast.show_ast ast in match Parser.parse_line string with @@ -251,23 +251,7 @@ let roundtrip_test_1 = | ParseError _ -> false) ;; -let roundtrip_test_2 = - Test.make - ~name:"Parser round-trip 2" - ~count:50 - (make ~print:Fun.id gen_expr) - (fun expr -> - match Parser.parse_line expr with - | Parsed (a, _) -> expr = Ast.show_ast a - | ParseError _ -> false) -;; - let%test "QCheck test" = - let res = - QCheck_runner.run_tests - ~long:true - ~verbose:true - [ roundtrip_test_1; roundtrip_test_2 ] - in + let res = QCheck_runner.run_tests ~long:true ~verbose:true [ roundtrip_test ] in res = 0 ;;