From 806b0890f0bd3e2b1524829b66af637a173c4f54 Mon Sep 17 00:00:00 2001 From: Ralf Treinen Date: Wed, 12 Feb 2020 21:02:06 +0100 Subject: Import morsmall_0.3.0.orig.tar.xz [dgit import orig morsmall_0.3.0.orig.tar.xz] --- .gitignore | 16 + .travis.yml | 15 + Dockerfile | 26 ++ LICENSE | 621 +++++++++++++++++++++++++++++++ Makefile | 33 ++ README.org | 39 ++ dune-project | 1 + morsmall.opam | 30 ++ src/.header | 18 + src/AST.ml | 248 +++++++++++++ src/CST_to_AST.ml | 859 +++++++++++++++++++++++++++++++++++++++++++ src/Makefile | 4 + src/dune | 6 + src/location.ml | 51 +++ src/morsmall.ml | 48 +++ src/morsmall.mli | 48 +++ src/safePrinter.ml | 274 ++++++++++++++ src/utilities/dune | 4 + src/utilities/testParser.ml | 244 ++++++++++++ src/utilities/testParser.mli | 37 ++ tests/dune | 4 + tests/generator.ml | 231 ++++++++++++ tests/generator.mli | 28 ++ tests/run.ml | 117 ++++++ 24 files changed, 3002 insertions(+) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.org create mode 100644 dune-project create mode 100644 morsmall.opam create mode 100644 src/.header create mode 100644 src/AST.ml create mode 100644 src/CST_to_AST.ml create mode 100644 src/Makefile create mode 100644 src/dune create mode 100644 src/location.ml create mode 100644 src/morsmall.ml create mode 100644 src/morsmall.mli create mode 100644 src/safePrinter.ml create mode 100644 src/utilities/dune create mode 100644 src/utilities/testParser.ml create mode 100644 src/utilities/testParser.mli create mode 100644 tests/dune create mode 100644 tests/generator.ml create mode 100644 tests/generator.mli create mode 100644 tests/run.ml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3b25b6e --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +## /.gitignore + +## Emacs specific +*~ +*# + +## Dune specific +_build +*.install +.merlin + +## Project specific +lib +doc +bin +morsmall_test_report_*.org diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..7210cb1 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,15 @@ +language: c +sudo: required +services: + - docker + +env: + - TAG=4.04 + - TAG=4.05 + - TAG=4.06 + - TAG=4.07 + - TAG=4.08 + +script: + - docker build --build-arg tag=$TAG --tag colisanr/morsmall:$TRAVIS_BRANCH . + - docker run --entrypoint /bin/sh colisanr/morsmall:$TRAVIS_BRANCH -c 'eval $(opam env) && cd /home/opam/morsmall && make install && make uninstall' diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4703087 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +## Get an OPAM image. By default, OCaml 4.06, but the tag can be +## changed by the `docker build` command line. + +ARG tag=4.06 +ARG image=ocaml/opam2:$tag +FROM $image +MAINTAINER Nicolas Jeannerod + +## Install dependencies. `opam depext` installs first the non-opam +## dependencies that are required and then the OPAM packages. + +RUN opam pin -n morbig.dev https://github.com/colis-anr/morbig.git +RUN opam depext -i morbig +ADD *.opam . +RUN opam install . --deps-only --with-test --with-doc + +## Work in /home/opam/morsmall, copy all the file there with the right +## owner and group. + +WORKDIR /home/opam/morsmall +ADD . . +RUN sudo chown -R opam . + +## Build + +RUN eval $(opam env) && make diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a0453 --- /dev/null +++ b/LICENSE @@ -0,0 +1,621 @@ + 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 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..60debd7 --- /dev/null +++ b/Makefile @@ -0,0 +1,33 @@ +.PHONY: build install uninstall doc tests clean + +ifneq ($(PREFIX),) +INSTALL_ARGS := $(INSTALL_ARGS) --prefix $(PREFIX) +endif + +ifneq ($(LIBDIR),) +INSTALL_ARGS := $(INSTALL_ARGS) --libdir $(LIBDIR) +endif + +build: + dune build @install +# ln -sf _build/install/default/bin bin + ln -sf _build/install/default/lib lib + +install: + dune install $(INSTALL_ARGS) + +uninstall: + dune uninstall $(INSTALL_ARGS) + +doc: + dune build @doc + ln -sf _build/default/_doc doc + +tests: + dune build tests/run.exe + _build/default/tests/run.exe + +clean: + dune clean + rm -f bin lib doc + rm -f morsmall_test_report_*.org diff --git a/README.org b/README.org new file mode 100644 index 0000000..3ce5cdf --- /dev/null +++ b/README.org @@ -0,0 +1,39 @@ +#+TITLE: Morsmall -- A concise AST for POSIX shell +#+STARTUP: indent inlineimages + +This library is a small wrapper around [[https://gitlab.inria.fr/regisgia/morbig/][morbig]]. Morbig provides a +parser and a CST representation of POSIX shell scripts which may +contain too much information for certain uses. + +Morsmall provides a converter from Morbig's CST to an AST that aims to +be easely understandable and manipulable. It also provides a printer +from that AST to Shell. + +This program is a free software licensed under the GNU General Public +License, version 3. Please refer to the file [[file:LICENSE][LICENSE]]. + +* Downloading, building and installing +** Download +*** Clone the repository +: git clone https://github.com/colis-anr/morsmall +*** Download the latest release +There is no release yet. +** Install dependencies +Morsmall depends on the following software: +- [[https://ocaml.org/][OCaml]] ≥ 4.04.0 +- [[https://github.com/colis-anr/morbig/][Morbig]] +- [[https://github.com/ocaml-ppx/ppx_deriving][ppx_deriving]] ≥ 4.2.0 +- [[https://github.com/ocaml/dune][Dune]] (ex jbuilder) with ocaml-migrate-parsetree +- [[http://opam.ocaml.org/][OPAM]] +** Build +: make +** Run tests +: make tests +** Install +: make install + +This target recognises the environment variables =PREFIX= and =LIBDIR=. +** Uninstall +: make uninstall + +This target recognises the environment variables =PREFIX= and =LIBDIR=. diff --git a/dune-project b/dune-project new file mode 100644 index 0000000..de4fc20 --- /dev/null +++ b/dune-project @@ -0,0 +1 @@ +(lang dune 1.0) diff --git a/morsmall.opam b/morsmall.opam new file mode 100644 index 0000000..fe9cb10 --- /dev/null +++ b/morsmall.opam @@ -0,0 +1,30 @@ +opam-version: "2.0" + +name: "Morsmall" +synopsis: "A concise AST for POSIX shell" +description: """ +A concise AST for POSIX shell +""" + +version: "0.2.0" +license: "GPL3" + +maintainer: "Nicolas Jeannerod " +authors: [ "Nicolas Jeannerod " ] + +homepage: "https://github.com/colis-anr/morsmall" +bug-reports: "https://github.com/colis-anr/morsmall/issues" +dev-repo: "git+ssh://git@github.com/colis-anr/morsmall.git" + +depends: [ + "dune" {build} + "morbig" {>= "0.10.0"} + "ocaml" {>= "4.04"} + "ppx_deriving" {build} + "ppx_deriving_yojson" {build} + "yojson" +] + +build: [ + ["dune" "build" "-p" name "-j" jobs] +] diff --git a/src/.header b/src/.header new file mode 100644 index 0000000..4b4bf97 --- /dev/null +++ b/src/.header @@ -0,0 +1,18 @@ + Morsmall + A concise AST for POSIX shell + +Copyright (C) 2017,2018,2019 Yann Régis-Gianas, Ralf Treinen, +Nicolas Jeannerod + +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 . diff --git a/src/AST.ml b/src/AST.ml new file mode 100644 index 0000000..44f9e3b --- /dev/null +++ b/src/AST.ml @@ -0,0 +1,248 @@ +(***************************************************************************) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017,2018,2019 Yann Régis-Gianas, Ralf Treinen, *) +(* Nicolas Jeannerod *) +(* *) +(* 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 . *) +(***************************************************************************) + +(** Names in Shell are just strings with a few additional + conditions. *) + +type name = string + +(** The type {!word} is a description of words in Shell. {e See POSIX, + 2 Shell & Utilities, 2.3 Token Recognition} *) + +and character_range = char list + +and attribute = + | NoAttribute + | ParameterLength of word + | UseDefaultValues of word + | AssignDefaultValues of word + | IndicateErrorifNullorUnset of word + | UseAlternativeValue of word + | RemoveSmallestSuffixPattern of word + | RemoveLargestSuffixPattern of word + | RemoveSmallestPrefixPattern of word + | RemoveLargestPrefixPattern of word + +and word_component = + | WTildePrefix of string + | WLiteral of string + | WDoubleQuoted of word + | WVariable of name * attribute + | WSubshell of program + | WGlobAll + | WGlobAny + | WBracketExpression of (Morbig.CST.bracket_expression [@equal (=)] [@opaque]) + +and word = word_component list +and word' = word Location.located + +(** For now, a {!pattern} is just a {!word}. *) + +and pattern = word list +and pattern' = pattern Location.located + +(** An assignment is just a pair of a {!name} and a {!word}. *) + +and assignment = name * word +and assignment' = assignment Location.located + +(** A file descriptor {!descr} is an integer. *) + +and descr = int + +(** The following description does contain all the semantic subtleties + of POSIX Shell. Such a description can be found in the document + {{:http://pubs.opengroup.org/onlinepubs/9699919799.2016edition/}IEEE + Std 1003.1™-2008, 2016 Edition}. In the following, we will refer to + it simple as POSIX. + + The type {!command} contains the definition of a Shell command in + Morsmall. Compared to what can be found in the POSIX standard or in + {{:https://github.com/colis-anr/morbig}Morbig}, this type is rather + small. This is because a lot of syntactically distinct scripts that + are semantically equivalent are identified in here. For instance, + all the following scripts are equivalent and identified as such: + {[ + if t1; then c1; elif t2; then c2; fi + if { t1; }; then c1; elif { { t2; }; }; fi + if t1; then c1; else if t2; then c2; fi; fi + ]} + + {2 Simple Command} + + {e See POSIX, 2 Shell & Utilities, 2.9.1 Simple Command} + + {2 Lists and Pipelines} + + {e See POSIX, 2 Shell & Utilities, 2.9.2 Pipelines and 2.9.3 Lists} + + - {b Asynchronous Lists.} When encountering [Async c], the Shell + shall execute [c] asynchronously in a subshell. This means that the + shell shall not wait for the command to finish before executing the + next command. + + - {b Sequential Lists.} {i A contrario}, the commands [c1] and [c2] + in [Seq (c1, c2)] shall be executed sequentially. + + - {b AND Lists.} In [And (c1, c2)], [c1] shall be executed + first. If its exit status is zero, [c2] shall be executed. The + commands are expanded only if they are executed. + + - {b OR Lists.} In [Or (c1, c2)], [c1] shall be executed first. If + its exit status is non-zero, [c2] shall be executed. + + - {b Pipeline.} In [Pipe (c1, c2)], the standard output of [c1] + shall be connected to the standard input of [c2]. The standard + input, standard output, or both of a command shall be considered to + be assigned by the pipeline before any redirection specified by + redirection operators that are part of the command. + + - {b Negation.} The command [Not c] has the same behaviour as [c], + except for the exit status that shall be the logical NOT of the + exit status of [c]. + + {2 Compound Commands} + + {e See POSIX, 2 Shell & Utilities, 2.9.4 Compound Commands} + + - {b The Subshell Environment.} [Subshell c] shall execute [c] a + subshell environment. Variable assignments and built-in commands + that affect the environment shall not remain in effect after the + list finishes. + + - {b The for Loop.} [For (x, l, c)] shall execute a sequence of + commands [c] for each member in a list of items. It is to be noted + that [l] is non-mandatory and is thus an option. Besides, there is + an important semantic difference between [None] and [Some + \[\]]. The former appears in a for loop where the list of words + appear but is empty. In that case, the for loops through the empty + list. The latter appears in a for loop where the list of words has + been omitted. In that case, the for loops through the positional + parameters. + + - {b The case Conditional Construct.} [Case (w, \[(\[p11;...\],c1); + ...\])] shall execute the compound-list corresponding to the first + one of several patterns that is matched by the string resulting + from the expansion of the given word [w]. In order from the + beginning to the end of the case statement, each pattern [p*] shall + be subjected to expansion, and the result of these expansions shall + be compared against the expansion of [w]. After the first match, no + more patterns shall be expanded, and the corresponding [c*] shall + be executed. The order of expansion and comparison of multiple + patterns that label the same statement is unspecified. + + - {b The if Conditional Construct.} [If (c1, c2, c3)] shall execute + [c1] and use its exit status to determine whether to execute [c2] + or [c3]. In fact, [c3] is not mandatory and is thus an option. + + - {b The while Loop.} [While (c1, c2)] shall continuously execute + [c2] as long as [c1] has a zero exit status. + + - {b The until Loop.} [Until (c1, c2)] shall continuously execute + [c2] as long as [c1] has a non-zero exit status. + + {2 Function Definition Command} + + {e See POSIX, 2 Shell & Utilities, 2.9.5 Function Definition + Command} + + A function is a user-defined name that is used as a simple command + to call a compound command with new positional parameters. A + function is defined with a {e function definition command}, + [Function (name, body)]. + + This function definition command defines a function named [name: + string] and with body [body: command]. The [body] shall be executed + whenever [name] is specified as the name of a simple command. + + {2 Redirection} + + {e See POSIX, 2 Shell & Utilities, 2.7 Redirections} + + *) + +(** {1 Type Definitions} + + The type [command] describes a command in the AST. All the command + semantics are described at the top of this document. *) + +and program = command' list + +and command = + (* Simple Commands *) + | Simple of assignment' list * word' list + + (* Lists *) + | Async of command + | Seq of command' * command' + | And of command' * command' + | Or of command' * command' + + (* Pipelines *) + | Not of command' + | Pipe of command' * command' + + (* Compound Command's *) + | Subshell of command' + | For of name * word list option * command' + | Case of word * case_item' list + | If of command' * command' * command' option + | While of command' * command' + | Until of command' * command' + + (* Function Definition Command' *) + | Function of name * command' + + (* Redirection *) + | Redirection of command' * descr * kind * word + | HereDocument of command' * descr * word' + +and command' = command Location.located + +and case_item = pattern' * command' option + +and case_item' = case_item Location.located + +and kind = + | Output (* > *) + | OutputDuplicate (* >& *) + | OutputAppend (* >> *) + | OutputClobber (* >| *) + | Input (* < *) + | InputDuplicate (* <& *) + | InputOutput (* <> *) + +[@@deriving + eq, + show {with_path=false}, + yojson {exn=true}, + visitors {variety = "iter"; ancestors=["Location.located_iter"]; nude=true}, + visitors {variety = "map"; ancestors=["Location.located_map"]; nude=true}, + visitors {variety = "reduce"; ancestors=["Location.located_reduce"]; nude=true}, + visitors {variety = "mapreduce"; ancestors=["Location.located_mapreduce"]; nude=true}, + visitors {variety = "iter2"; ancestors=["Location.located_iter2"]; nude=true}, + visitors {variety = "map2"; ancestors=["Location.located_map2"]; nude=true}, + visitors {variety = "reduce2"; ancestors=["Location.located_reduce2"]; nude=true} +] + +let default_redirection_descriptor = function + | Output | OutputDuplicate | OutputAppend | OutputClobber -> 1 + | Input | InputDuplicate | InputOutput -> 0 diff --git a/src/CST_to_AST.ml b/src/CST_to_AST.ml new file mode 100644 index 0000000..8890c9a --- /dev/null +++ b/src/CST_to_AST.ml @@ -0,0 +1,859 @@ +(***************************************************************************) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017,2018,2019 Yann Régis-Gianas, Ralf Treinen, *) +(* Nicolas Jeannerod *) +(* *) +(* 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 . *) +(***************************************************************************) + +open Morbig.CST + +(* Helpers about locations. *) + +let convert_location : 'a 'b. ('a -> 'b) -> 'a located -> 'b Location.located = + fun f loc -> { value = f loc.value ; position = loc.position } + +let convert_location_2 : 'a 'b 'c. ('a -> 'b -> 'c) -> 'a located -> 'b -> 'c Location.located = + fun f loc x -> + { value = f loc.value x ; position = loc.position } + +let erase_location : 'a 'b. ('a -> 'b) -> 'a located -> 'b = + fun f x -> f x.value + +(* Convertion functions *) + +(* CST.program -> AST.program *) + +let rec program__to__program = function + | Program_LineBreak_CompleteCommands_LineBreak (_, complete_commands', _) -> + complete_commands'__to__command'_list complete_commands' + | Program_LineBreak _ -> + [] + +and program'__to__program (program' : program') : AST.program = + erase_location program__to__program program' + +(* CST.complete_commands -> AST.command list *) + +and complete_commands__to__command_list = function + | CompleteCommands_CompleteCommands_NewlineList_CompleteCommand (complete_commands', _, complete_command') -> + (complete_commands'__to__command'_list complete_commands') + @ [complete_command'__to__command' complete_command'] + | CompleteCommands_CompleteCommand complete_command' -> + [complete_command'__to__command' complete_command'] + +and complete_commands'__to__command'_list (complete_commands' : complete_commands') : AST.command' list = + erase_location complete_commands__to__command_list complete_commands' + +(* CST.complete_command -> AST.command option *) + +and complete_command__to__command = function + | CompleteCommand_CList_SeparatorOp (clist', sepop') -> + clist'__to__command clist' + |> separator_op'__to__command sepop' + | CompleteCommand_CList clist' -> + clist'__to__command clist' + +and complete_command'__to__command' (complete_command' : complete_command') : AST.command' = + convert_location complete_command__to__command complete_command' + +(* CST.clist -> AST.command *) + +and clist__to__command : clist -> AST.command = function + | CList_CList_SeparatorOp_AndOr (clist', sep_op', and_or') -> + AST.Seq ( + clist'__to__command' clist' + |> separator_op'__to__command' sep_op', + and_or'__to__command' and_or' + ) + | CList_AndOr and_or' -> + and_or'__to__command and_or' + +and clist'__to__command (clist' : clist') : AST.command = + erase_location clist__to__command clist' + +and clist'__to__command' (clist' : clist') : AST.command' = + convert_location clist__to__command clist' + +(* CST.and_or -> AST.command *) + +and and_or__to__command : and_or -> AST.command = function + | AndOr_Pipeline pipeline' -> + pipeline'__to__command pipeline' + | AndOr_AndOr_AndIf_LineBreak_Pipeline (and_or', _, pipeline') -> + AST.And ( + and_or'__to__command' and_or', + pipeline'__to__command' pipeline' + ) + | AndOr_AndOr_OrIf_LineBreak_Pipeline (and_or', _, pipeline') -> + AST.Or ( + and_or'__to__command' and_or', + pipeline'__to__command' pipeline' + ) + +and and_or'__to__command (and_or' : and_or') : AST.command = + erase_location and_or__to__command and_or' + +and and_or'__to__command' (and_or' : and_or') : AST.command' = + convert_location and_or__to__command and_or' + +(* CST.pipeline -> AST.command *) + +and pipeline__to__command : pipeline -> AST.command = function + | Pipeline_PipeSequence pipe_sequence' -> + pipe_sequence'__to__command pipe_sequence' + | Pipeline_Bang_PipeSequence pipe_sequence' -> + AST.Not (pipe_sequence'__to__command' pipe_sequence') + +and pipeline'__to__command (pipeline' : pipeline') : AST.command = + erase_location pipeline__to__command pipeline' + +and pipeline'__to__command' (pipeline' : pipeline') : AST.command' = + convert_location pipeline__to__command pipeline' + +(* CST.pipe_sequence -> AST.command *) + +and pipe_sequence__to__command : pipe_sequence -> AST.command = function + | PipeSequence_Command command' -> + command'__to__command command' + | PipeSequence_PipeSequence_Pipe_LineBreak_Command (pipe_sequence', _, command') -> + AST.Pipe ( + pipe_sequence'__to__command' pipe_sequence', + command'__to__command' command' + ) + +and pipe_sequence'__to__command (pipe_sequence') : AST.command = + erase_location pipe_sequence__to__command pipe_sequence' + +and pipe_sequence'__to__command' (pipe_sequence') : AST.command' = + convert_location pipe_sequence__to__command pipe_sequence' + +(* CST.command -> AST.command *) + +and command__to__command : command -> AST.command = function + | Command_SimpleCommand simple_command' -> + simple_command'__to__command simple_command' + | Command_CompoundCommand compound_command' -> + compound_command'__to__command compound_command' + | Command_CompoundCommand_RedirectList (compound_command', redirect_list') -> + compound_command'__to__command' compound_command' + |> redirect_list'__to__command redirect_list' + | Command_FunctionDefinition function_definition' -> + function_definition'__to__command function_definition' + +and command'__to__command (command' : command') : AST.command = + erase_location command__to__command command' + +and command'__to__command' (command' : command') : AST.command' = + convert_location command__to__command command' + +(* CST.compound_command -> AST.command *) + +and compound_command__to__command : compound_command -> AST.command = function + | CompoundCommand_BraceGroup brace_group' -> + brace_group'__to__command brace_group' + | CompoundCommand_Subshell subshell' -> + subshell'__to__command subshell' + | CompoundCommand_ForClause for_clause' -> + for_clause'__to__command for_clause' + | CompoundCommand_CaseClause case_clause' -> + case_clause'__to__command case_clause' + | CompoundCommand_IfClause if_clause' -> + if_clause'__to__command if_clause' + | CompoundCommand_WhileClause while_clause' -> + while_clause'__to__command while_clause' + | CompoundCommand_UntilClause until_clause' -> + until_clause'__to__command until_clause' + +and compound_command'__to__command (compound_command' : compound_command') : AST.command = + erase_location compound_command__to__command compound_command' + +and compound_command'__to__command' (compound_command' : compound_command') : AST.command' = + convert_location compound_command__to__command compound_command' + +(* CST.subshell -> AST.command *) + +and subshell__to__command : subshell -> AST.command = function + | Subshell_Lparen_CompoundList_Rparen compound_list' -> + AST.Subshell (compound_list'__to__command' compound_list') + +and subshell'__to__command (subshell' : subshell') : AST.command = + erase_location subshell__to__command subshell' + +(* CST.compound_list -> AST.command *) + +and compound_list__to__command : compound_list -> AST.command = function + | CompoundList_LineBreak_Term (_, term') -> + term'__to__command term' + | CompoundList_LineBreak_Term_Separator (_, term', sep') -> + term'__to__command term' + |> separator'__to__command sep' + +and compound_list'__to__command (compound_list' : compound_list') : AST.command = + erase_location compound_list__to__command compound_list' + +and compound_list'__to__command' (compound_list' : compound_list') : AST.command' = + convert_location compound_list__to__command compound_list' + +(* CST.term -> AST.command *) + +and term__to__command : term -> AST.command = function + | Term_Term_Separator_AndOr (term', sep', and_or') -> + AST.Seq ( + term'__to__command' term' + |> separator'__to__command' sep', + and_or'__to__command' and_or' + ) + | Term_AndOr and_or' -> + and_or'__to__command and_or' + +and term'__to__command (term' : term') : AST.command = + erase_location term__to__command term' + +and term'__to__command' (term' : term') : AST.command' = + convert_location term__to__command term' + +(* CST.for_clause -> AST.command *) + +and for_clause__to__command : for_clause -> AST.command = function + | ForClause_For_Name_DoGroup (name', do_group') + | ForClause_For_Name_SequentialSep_DoGroup (name', _, do_group') -> + AST.For ( + name'__to__name name' , + None , + do_group'__to__command' do_group' + ) + | ForClause_For_Name_LineBreak_In_SequentialSep_DoGroup (name', _, _, do_group') -> + AST.For ( + name'__to__name name' , + Some [] , + do_group'__to__command' do_group' + ) + | ForClause_For_Name_LineBreak_In_WordList_SequentialSep_DoGroup (name', _, wordlist', _, do_group') -> + AST.For ( + name'__to__name name' , + Some (wordlist'__to__word_list wordlist') , + do_group'__to__command' do_group' + ) + +and for_clause'__to__command (for_clause' : for_clause') : AST.command = + erase_location for_clause__to__command for_clause' + +(* CST.wordlist -> AST.word list *) + +and wordlist__to__word_list : wordlist -> AST.word list = function (*FIXME*) + | WordList_WordList_Word (wordlist', word') -> + (wordlist'__to__word_list wordlist') + @ [word'__to__word word'] + | WordList_Word word' -> + [word'__to__word word'] + +and wordlist'__to__word_list (wordlist' : wordlist') : AST.word list = + erase_location wordlist__to__word_list wordlist' + +(* CST.case_clause -> AST.command *) + +and case_clause__to__command : case_clause -> AST.command = function + | CaseClause_Case_Word_LineBreak_In_LineBreak_CaseList_Esac (word', _, _, case_list') -> + AST.Case ( + word'__to__word word' , + case_list'__to__case_item'_list case_list' + ) + | CaseClause_Case_Word_LineBreak_In_LineBreak_CaseListNS_Esac (word', _, _, case_list_ns') -> + AST.Case ( + word'__to__word word' , + case_list_ns'__to__case_item'_list case_list_ns' + ) + | CaseClause_Case_Word_LineBreak_In_LineBreak_Esac (word', _, _) -> + AST.Case ( + word'__to__word word' , + [] + ) + +and case_clause'__to__command (case_clause' : case_clause') : AST.command = + erase_location case_clause__to__command case_clause' + +(* CST.case_list_ns -> AST.case list *) + +and case_list_ns__to__case_item'_list : case_list_ns -> AST.case_item' list = function (*FIXME*) + | CaseListNS_CaseList_CaseItemNS (case_list', case_item_ns') -> + (case_list'__to__case_item'_list case_list') + @ [case_item_ns'__to__case_item' case_item_ns'] + | CaseListNS_CaseItemNS case_item_ns' -> + [case_item_ns'__to__case_item' case_item_ns'] + +and case_list_ns'__to__case_item'_list (case_list_ns' : case_list_ns') : AST.case_item' list = + erase_location case_list_ns__to__case_item'_list case_list_ns' + +(* CST.case_list -> AST.case list *) + +and case_list__to__case_item'_list : case_list -> AST.case_item' list = function (*FIXME*) + | CaseList_CaseList_CaseItem (case_list', case_item') -> + (case_list'__to__case_item'_list case_list') + @ [case_item'__to__case_item' case_item'] + | CaseList_CaseItem case_item' -> + [case_item'__to__case_item' case_item'] + +and case_list'__to__case_item'_list (case_list' : case_list') : AST.case_item' list = + erase_location case_list__to__case_item'_list case_list' + +(* CST.case_item_ns -> AST.case_item *) + +and case_item_ns__to__case_item : case_item_ns -> AST.case_item = function + | CaseItemNS_Pattern_Rparen_LineBreak (pattern', _) + | CaseItemNS_Lparen_Pattern_Rparen_LineBreak (pattern', _) -> + (pattern'__to__pattern' pattern', None) + | CaseItemNS_Pattern_Rparen_CompoundList (pattern', compound_list') + | CaseItemNS_Lparen_Pattern_Rparen_CompoundList (pattern', compound_list') -> + (pattern'__to__pattern' pattern', Some (compound_list'__to__command' compound_list')) + +and case_item_ns'__to__case_item' (case_item_ns' : case_item_ns') : AST.case_item' = + convert_location case_item_ns__to__case_item case_item_ns' + +(* CST.case_item -> AST.case_item *) + +and case_item__to__case_item : case_item -> AST.case_item = function + | CaseItem_Pattern_Rparen_LineBreak_Dsemi_LineBreak (pattern', _, _) + | CaseItem_Lparen_Pattern_Rparen_LineBreak_Dsemi_LineBreak (pattern', _, _) -> + (pattern'__to__pattern' pattern', None) + | CaseItem_Pattern_Rparen_CompoundList_Dsemi_LineBreak (pattern', compound_list', _) + | CaseItem_Lparen_Pattern_Rparen_CompoundList_Dsemi_LineBreak (pattern', compound_list', _) -> + (pattern'__to__pattern' pattern', Some (compound_list'__to__command' compound_list')) + +and case_item'__to__case_item' (case_item' : case_item') : AST.case_item' = + convert_location case_item__to__case_item case_item' + +(* CST.pattern -> AST.pattern *) + +and pattern__to__pattern : pattern -> AST.pattern = function + | Pattern_Word word' -> + [word'__to__word word'] + | Pattern_Pattern_Pipe_Word (pattern', word') -> + (pattern'__to__pattern pattern') + @ [word'__to__word word'] + +and pattern'__to__pattern (pattern' : pattern') : AST.pattern = + erase_location pattern__to__pattern pattern' + +and pattern'__to__pattern' (pattern' : pattern') : AST.pattern' = + convert_location pattern__to__pattern pattern' + +(* CST.if_clause -> AST.command *) + +and if_clause__to__command : if_clause -> AST.command = function + | IfClause_If_CompoundList_Then_CompoundList_ElsePart_Fi (compound_list', compound_list2', else_part') -> + AST.If ( + compound_list'__to__command' compound_list' , + compound_list'__to__command' compound_list2' , + Some (else_part'__to__command' else_part') + ) + | IfClause_If_CompoundList_Then_CompoundList_Fi (compound_list', compound_list2') -> + AST.If ( + compound_list'__to__command' compound_list' , + compound_list'__to__command' compound_list2' , + None + ) + +and if_clause'__to__command (if_clause' : if_clause') : AST.command = + erase_location if_clause__to__command if_clause' + +(* CST.else_part -> AST.command *) + +and else_part__to__command : else_part -> AST.command = function + | ElsePart_Elif_CompoundList_Then_CompoundList (compound_list', compound_list2') -> + AST.If ( + compound_list'__to__command' compound_list' , + compound_list'__to__command' compound_list2' , + None + ) + | ElsePart_Elif_CompoundList_Then_CompoundList_ElsePart (compound_list', compound_list2', else_part') -> + AST.If ( + compound_list'__to__command' compound_list' , + compound_list'__to__command' compound_list2' , + Some (else_part'__to__command' else_part') + ) + | ElsePart_Else_CompoundList compound_list' -> + compound_list'__to__command compound_list' + +and else_part'__to__command' (else_part' : else_part') : AST.command' = + convert_location else_part__to__command else_part' + +(* CST.while_clause -> AST.command *) + +and while_clause__to__command : while_clause -> AST.command = function + | WhileClause_While_CompoundList_DoGroup (compound_list', do_group') -> + AST.While ( + compound_list'__to__command' compound_list' , + do_group'__to__command' do_group' + ) + +and while_clause'__to__command (while_clause' : while_clause') : AST.command = + erase_location while_clause__to__command while_clause' + +(* CST.until_clause -> AST.command *) + +and until_clause__to__command : until_clause -> AST.command = function + | UntilClause_Until_CompoundList_DoGroup (compound_list', do_group') -> + AST.Until ( + compound_list'__to__command' compound_list' , + do_group'__to__command' do_group' + ) + +and until_clause'__to__command (until_clause' : until_clause') : AST.command = + erase_location until_clause__to__command until_clause' + +(* CST.function_definition -> AST.command *) + +and function_definition__to__command : function_definition -> AST.command = function + | FunctionDefinition_Fname_Lparen_Rparen_LineBreak_FunctionBody (fname', _, function_body') -> + AST.Function ( + fname'__to__name fname' , + function_body'__to__command' function_body' + ) + +and function_definition'__to__command (function_definition' : function_definition') : AST.command = + erase_location function_definition__to__command function_definition' + +(* CST.function_body -> AST.command *) + +and function_body__to__command : function_body -> AST.command = function + | FunctionBody_CompoundCommand compound_command' -> + compound_command'__to__command compound_command' + | FunctionBody_CompoundCommand_RedirectList (compound_command', redirect_list') -> + compound_command'__to__command' compound_command' + |> redirect_list'__to__command redirect_list' + +and function_body'__to__command' (function_body' : function_body') : AST.command' = + convert_location function_body__to__command function_body' + +(* CST.fname -> AST.name *) + +and fname__to__name : fname -> AST.name = function + | Fname_Name name -> name__to__name name + +and fname'__to__name (fname' : fname') : AST.name = + erase_location fname__to__name fname' + +(* CST.brace_group -> AST.command *) + +and brace_group__to__command : brace_group -> AST.command = function + | BraceGroup_LBrace_CompoundList_RBrace compound_list' -> + compound_list'__to__command compound_list' + +and brace_group'__to__command (brace_group' : brace_group') : AST.command = + erase_location brace_group__to__command brace_group' + +(* CST.do_group -> AST.command *) + +and do_group__to__command : do_group -> AST.command = function + | DoGroup_Do_CompoundList_Done compound_list' -> + compound_list'__to__command compound_list' + +and do_group'__to__command' (do_group' : do_group') : AST.command' = + convert_location do_group__to__command do_group' + +(* CST.simple_command -> AST.command *) + +and simple_command'__to__command (simple_command' : simple_command') : AST.command = + let ( assignment'_list , word'_list , io_redirect'_list ) = + match simple_command'.value with + | SimpleCommand_CmdPrefix_CmdWord_CmdSuffix (cmd_prefix', cmd_word', cmd_suffix') -> + (* Since we are sorting right-to-left, we need to sort the + suffix before the prefix. *) + let ( word'_list , io_redirect'_list ) = sort__cmd_suffix' [] [] cmd_suffix' in + let ( assignment_word'_list , io_redirect'_list ) = sort__cmd_prefix' [] io_redirect'_list cmd_prefix' in + ( + List.map assignment_word'__to__assignment' assignment_word'_list , + cmd_word'__to__word' cmd_word' :: List.map word'__to__word' word'_list , + io_redirect'_list + ) + + | SimpleCommand_CmdPrefix_CmdWord (cmd_prefix', cmd_word') -> + let ( assignment_word'_list , io_redirect'_list ) = sort__cmd_prefix' [] [] cmd_prefix' in + ( + List.map assignment_word'__to__assignment' assignment_word'_list , + cmd_word'__to__word' cmd_word' :: [] , + io_redirect'_list + ) + + | SimpleCommand_CmdPrefix cmd_prefix' -> + let ( assignment_word'_list , io_redirect'_list ) = sort__cmd_prefix' [] [] cmd_prefix' in + ( List.map assignment_word'__to__assignment' assignment_word'_list , + [] , + io_redirect'_list ) + + | SimpleCommand_CmdName_CmdSuffix (cmd_name', cmd_suffix') -> + let ( word'_list , io_redirect'_list ) = sort__cmd_suffix' [] [] cmd_suffix' in + ( [] , + cmd_name'__to__word' cmd_name' :: List.map word'__to__word' word'_list , + io_redirect'_list ) + + | SimpleCommand_CmdName cmd_name' -> + ( [] , + cmd_name'__to__word' cmd_name' :: [] , + [] ) + in + (* Because of the semantics of redirections, we need to handle that + redirection list from right to left. *) + List.fold_right + ( + fun io_redirect' command -> + io_redirect'__to__command + io_redirect' + { value = command ; + position = simple_command'.position } + ) + io_redirect'_list + (AST.Simple (assignment'_list, word'_list )) + +(* CST.cmd_prefix -> CST.assignment_word' list * CST.io_redirect' list + + This function takes a prefix (which is basically a list of either + CST.assignment_word' or CST.io_redirect' and return two separate + lists for these two type of elements. It uses accumulators, but + since we are converting right-to-left lists to left-to-right lists, + we do not need a List.rev. *) + +and sort__cmd_prefix (assignment_word'_acc : assignment_word' list) (io_redirect'_acc : io_redirect' list) (*FIXME: check order*) + : cmd_prefix -> assignment_word' list * io_redirect' list = function + | CmdPrefix_IoRedirect io_redirect' -> + ( assignment_word'_acc , + io_redirect' :: io_redirect'_acc ) + + | CmdPrefix_CmdPrefix_IoRedirect (cmd_prefix', io_redirect') -> + sort__cmd_prefix' + assignment_word'_acc + (io_redirect' :: io_redirect'_acc) + cmd_prefix' + + | CmdPrefix_AssignmentWord assignment_word' -> + ( assignment_word' :: assignment_word'_acc , + io_redirect'_acc ) + + | CmdPrefix_CmdPrefix_AssignmentWord (cmd_prefix', assignment_word') -> + sort__cmd_prefix' + (assignment_word' :: assignment_word'_acc) + io_redirect'_acc + cmd_prefix' + +and sort__cmd_prefix' (assignment_word'_acc : assignment_word' list) (io_redirect'_acc : io_redirect' list) + (cmd_prefix' : cmd_prefix') : assignment_word' list * io_redirect' list = + sort__cmd_prefix assignment_word'_acc io_redirect'_acc cmd_prefix'.value + +(* CST.cmd_suffix -> CST.word' list * CST.io_redirect' list + + This function takes a suffix (which is basically a list of either + CST.word' or CST.io_redirect' and return two separate lists for + these two type of elements. It uses accumulators, but since we are + converting right-to-left lists to left-to-right lists, we do not + need a List.rev. *) + +and sort__cmd_suffix (word'_acc : word' list) (io_redirect'_acc : io_redirect' list) + : cmd_suffix -> word' list * io_redirect' list = function + | CmdSuffix_IoRedirect io_redirect' -> + ( word'_acc , + io_redirect' :: io_redirect'_acc ) + + | CmdSuffix_CmdSuffix_IoRedirect (cmd_suffix', io_redirect') -> + sort__cmd_suffix' + word'_acc + (io_redirect' :: io_redirect'_acc) + cmd_suffix' + + | CmdSuffix_Word word' -> + ( word' :: word'_acc , + io_redirect'_acc ) + + | CmdSuffix_CmdSuffix_Word (cmd_suffix', word') -> + sort__cmd_suffix' + (word' :: word'_acc) + io_redirect'_acc + cmd_suffix' + +and sort__cmd_suffix' (word'_acc : word' list) (io_redirect'_acc : io_redirect' list) + (cmd_suffix' : cmd_suffix') : word' list * io_redirect' list = + sort__cmd_suffix word'_acc io_redirect'_acc cmd_suffix'.value + +(* CST.cmd_name -> AST.word *) + +and cmd_name__to__word : cmd_name -> AST.word = function + | CmdName_Word word' -> + word'__to__word word' + +and cmd_name'__to__word' (cmd_name' : cmd_name') : AST.word' = + convert_location cmd_name__to__word cmd_name' + +(* CST.cmd_word -> AST.word *) + +and cmd_word__to__word : cmd_word -> AST.word = function + | CmdWord_Word word' -> + word'__to__word word' + +and cmd_word'__to__word' (cmd_word' : cmd_word') : AST.word' = + convert_location cmd_word__to__word cmd_word' + +(* CST.redirect_list -> AST.command' -> AST.command *) + +and redirect_list__to__command redirect_list (command' : AST.command') : AST.command = + match redirect_list with + | RedirectList_IoRedirect io_redirect' -> + command' + |> io_redirect'__to__command io_redirect' + | RedirectList_RedirectList_IoRedirect (redirect_list', io_redirect') -> + command' + |> io_redirect'__to__command' io_redirect' + |> redirect_list'__to__command redirect_list' (*FIXME: check order of the redirections*) + +and redirect_list'__to__command (redirect_list' : redirect_list') (command' : AST.command') : AST.command = + erase_location redirect_list__to__command redirect_list' command' + +(* CST.io_redirect -> AST.command' -> AST.command *) + +and io_redirect__to__command (io_redirect : io_redirect) (command' : AST.command') : AST.command = + match io_redirect with + | IoRedirect_IoFile io_file' -> + let kind, word = io_file'__to__kind_word io_file' in + AST.Redirection ( + command' , + (AST.default_redirection_descriptor kind) , + kind , + word + ) + | IoRedirect_IoNumber_IoFile (io_number, io_file') -> + let kind, word = io_file'__to__kind_word io_file' in + AST.Redirection ( + command' , + (io_number__to__int io_number) , + kind , + word + ) + | IoRedirect_IoHere io_here' -> + let _strip, word' = io_here'__to__strip_word' io_here' in + AST.HereDocument ( + command' , + 0 , + word' (* FIXME: strip that word if needed *) + ) + | IoRedirect_IoNumber_IoHere (io_number, io_here') -> + let _strip, word' = io_here'__to__strip_word' io_here' in + AST.HereDocument ( + command' , + (io_number__to__int io_number) , + word' (* FIXME: strip that word if needed *) + ) + +and io_redirect'__to__command (io_redirect' : io_redirect') (command' : AST.command') : AST.command = + erase_location io_redirect__to__command io_redirect' command' + +and io_redirect'__to__command' (io_redirect' : io_redirect') (command' : AST.command') : AST.command' = + convert_location_2 io_redirect__to__command io_redirect' command' + +(* CST.io_file -> AST.redirection_kind * AST.word *) + +and io_file__to__kind_word io_file = + let kind, filename' = + match io_file with + | IoFile_Less_FileName filename' -> AST.Input, filename' + | IoFile_LessAnd_FileName filename' -> AST.InputDuplicate, filename' + | IoFile_Great_FileName filename' -> AST.Output, filename' + | IoFile_GreatAnd_FileName filename' -> AST.OutputDuplicate, filename' + | IoFile_DGreat_FileName filename' -> AST.OutputAppend, filename' + | IoFile_LessGreat_FileName filename' -> AST.InputOutput, filename' + | IoFile_Clobber_FileName filename' -> AST.OutputClobber, filename' + in + ( kind , filename'__to__word filename' ) + +and io_file'__to__kind_word (io_file' : io_file') : AST.kind * AST.word = + erase_location io_file__to__kind_word io_file' + +(* CST.filename -> AST.word *) + +and filename__to__word : filename -> AST.word = function + | Filename_Word word' -> + word'__to__word word' + +and filename'__to__word (filename' : filename') : AST.word = + erase_location filename__to__word filename' + +(* CST.io_here -> bool * AST.word *) + +and io_here__to__strip_word' : io_here -> bool * AST.word' = function + | IoHere_DLess_HereEnd (_, word'_ref) -> + (false, word'__to__word' !word'_ref) + | IoHere_DLessDash_HereEnd (_, word'_ref) -> + (true, word'__to__word' !word'_ref) + +and io_here'__to__strip_word' (io_here' : io_here') : bool * AST.word' = + erase_location io_here__to__strip_word' io_here' + +(* CST.separator_op -> AST.command -> AST.command *) + +and separator_op__to__command (sep_op : separator_op) (command : AST.command) : AST.command = + match sep_op with + | SeparatorOp_Uppersand -> AST.Async command + | SeparatorOp_Semicolon -> command + +and separator_op'__to__command (sep_op' : separator_op') (command : AST.command) : AST.command = + erase_location separator_op__to__command sep_op' command + +and separator_op'__to__command' (sep_op' : separator_op') (command' : AST.command') : AST.command' = + (* We do not want to convert the separator's location here but + rather use the command's location! *) + { value = separator_op__to__command sep_op'.value command'.value ; + position = command'.position } + +(* CST.separator -> AST.command -> AST.command *) + +and separator__to__command (sep : separator) (command : AST.command) : AST.command = + match sep with + | Separator_SeparatorOp_LineBreak (sep_op', _) -> + separator_op'__to__command sep_op' command + | Separator_NewLineList _ -> + command + +and separator'__to__command (sep' : separator') (command : AST.command) : AST.command = + erase_location separator__to__command sep' command + +and separator'__to__command' (sep' : separator') (command' : AST.command') : AST.command' = + (* We do not want to convert the separator's location here but + rather use the command's location! *) + { value = separator__to__command sep'.value command'.value ; + position = command'.position } + +(* *) + +and sequential_sep__to__command _ (command : AST.command) : AST.command = + command + +(* CST.word -> AST.word *) + +and word__to__word : word -> AST.word = function + | Word (_, word_cst) -> + word_cst__to__word word_cst + +and word'__to__word (word' : word') : AST.word = + erase_location word__to__word word' + +and word'__to__word' (word' : word') : AST.word' = + convert_location word__to__word word' + +and word_double_quoted__to__word (Word (_, word_cst)) = + word_cst_double_quoted__to__word word_cst + +(* CST.word_cst -> AST.word *) + +and word_cst__to__word (word_cst : word_cst) : AST.word = + List.map word_component__to__word word_cst + |> List.flatten + +and word_cst_double_quoted__to__word (word_cst : word_cst) : AST.word = + List.map word_component_double_quoted__to__word word_cst + |> List.flatten + +(* CST.word_component -> AST.word_component *) + +and word_component__to__word = function + | WordEmpty -> + [] + | WordName name -> + [AST.WLiteral name] + | WordTildePrefix prefix -> + [AST.WTildePrefix prefix] + | WordLiteral literal -> + [AST.WLiteral literal] + | WordAssignmentWord (Name name, Word (_, word_cst)) -> + [AST.WLiteral name; AST.WLiteral "="] + @ word_cst__to__word word_cst + | WordSingleQuoted (Word (_, [WordLiteral literal])) -> + [AST.WLiteral literal] + | WordSingleQuoted (Word (_, [])) -> + [AST.WLiteral ""] + | WordSingleQuoted _ -> + assert false + | WordSubshell (_, program') -> + [AST.WSubshell (program'__to__program program')] + | WordDoubleQuoted word -> + [AST.WDoubleQuoted (word_double_quoted__to__word word)] + | WordVariable (VariableAtom (name, variable_attribute)) -> + [AST.WVariable (name, variable_attribute__to__attribute variable_attribute)] + | WordGlobAll -> + [AST.WGlobAll] + | WordGlobAny -> + [AST.WGlobAny] + | WordReBracketExpression bracket_expression -> + [AST.WBracketExpression bracket_expression] + +and word_component_double_quoted__to__word = function + | WordEmpty -> + [] + | WordName literal | WordLiteral literal | WordTildePrefix literal -> + [AST.WLiteral literal] + | WordSubshell (_, program') -> + [AST.WSubshell (program'__to__program program')] + | WordAssignmentWord (Name name, Word (_, word_cst)) -> + [AST.WLiteral name; AST.WLiteral "="] + @ word_cst_double_quoted__to__word word_cst + | WordVariable (VariableAtom (name, variable_attribute)) -> + [AST.WVariable (name, variable_attribute__to__attribute variable_attribute)] + | WordReBracketExpression bracket_expression -> + [AST.WBracketExpression bracket_expression] + | WordDoubleQuoted _ | WordSingleQuoted _ + | WordGlobAll | WordGlobAny -> + assert false + +and variable_attribute__to__attribute = function + | NoAttribute -> + AST.NoAttribute + | ParameterLength word -> + AST.ParameterLength (word__to__word word) + | UseDefaultValues (_, word) -> + AST.UseDefaultValues (word__to__word word) + | AssignDefaultValues (_, word) -> + AST.AssignDefaultValues (word__to__word word) + | IndicateErrorifNullorUnset (_, word) -> + AST.IndicateErrorifNullorUnset (word__to__word word) + | UseAlternativeValue (_, word) -> + AST.UseAlternativeValue (word__to__word word) + | RemoveSmallestSuffixPattern word -> + AST.RemoveSmallestSuffixPattern (word__to__word word) + | RemoveLargestSuffixPattern word -> + AST.RemoveLargestSuffixPattern (word__to__word word) + | RemoveSmallestPrefixPattern word -> + AST.RemoveSmallestPrefixPattern (word__to__word word) + | RemoveLargestPrefixPattern word -> + AST.RemoveLargestPrefixPattern (word__to__word word) + +(* CST.name -> AST.name *) + +and name__to__name : name -> AST.name = function + | Name name -> name + +and name'__to__name (name' : name') : AST.name = + erase_location name__to__name name' + +(* CST.assignment_word -> AST.assignment *) + +and assignment_word__to__assignment ((name, word) : assignment_word) : AST.assignment = + (name__to__name name, + word__to__word word) + +and assignment_word'__to__assignment' (assignment_word' : assignment_word') : AST.assignment' = + convert_location assignment_word__to__assignment assignment_word' + +(* CST.io_number -> AST.descr *) + +and io_number__to__int = function + | IONumber io_number -> int_of_string io_number diff --git a/src/Makefile b/src/Makefile new file mode 100644 index 0000000..a83741e --- /dev/null +++ b/src/Makefile @@ -0,0 +1,4 @@ +default: + +headers: + headache -h .header *.ml *.mli utilities/*.ml utilities/*.mli diff --git a/src/dune b/src/dune new file mode 100644 index 0000000..4053a9f --- /dev/null +++ b/src/dune @@ -0,0 +1,6 @@ +(library + (name morsmall) + (public_name morsmall) + (preprocess (pps ppx_deriving.std visitors.ppx ppx_deriving_yojson)) + (libraries morbig morsmall.utilities visitors.runtime yojson) + (flags :standard -w +A-4-30-42)) diff --git a/src/location.ml b/src/location.ml new file mode 100644 index 0000000..474ae35 --- /dev/null +++ b/src/location.ml @@ -0,0 +1,51 @@ +(***************************************************************************) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017,2018,2019 Yann Régis-Gianas, Ralf Treinen, *) +(* Nicolas Jeannerod *) +(* *) +(* 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 . *) +(***************************************************************************) + +type lexing_position = Morbig.CST.lexing_position = + { pos_fname : string ; + pos_lnum : int ; + pos_bol : int ; + pos_cnum : int } +[@@deriving eq, show {with_path=false}, yojson] + +type position = Morbig.CST.position = + { start_p : lexing_position ; + end_p : lexing_position } +[@@deriving eq, show {with_path=false}, yojson] + +type 'a located = 'a Morbig.CST.located = + { value : 'a ; + position : position } +[@@deriving eq, show {with_path=false}, yojson] + +class virtual ['a] located_iter = ['a] Morbig.CST.located_iter +class virtual ['a] located_map = ['a] Morbig.CST.located_map +class virtual ['a] located_reduce = ['a] Morbig.CST.located_reduce +class virtual ['a] located_mapreduce = ['a] Morbig.CST.located_mapreduce +class virtual ['a] located_iter2 = ['a] Morbig.CST.located_iter2 +class virtual ['a] located_map2 = ['a] Morbig.CST.located_map2 +class virtual ['a] located_reduce2 = ['a] Morbig.CST.located_reduce2 + +let dummily_located value = + { value ; position = Morbig.CSTHelpers.dummy_position } + +let on_located f v = + f v.value diff --git a/src/morsmall.ml b/src/morsmall.ml new file mode 100644 index 0000000..318ede9 --- /dev/null +++ b/src/morsmall.ml @@ -0,0 +1,48 @@ +(***************************************************************************) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017,2018,2019 Yann Régis-Gianas, Ralf Treinen, *) +(* Nicolas Jeannerod *) +(* *) +(* 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 . *) +(***************************************************************************) + +exception SyntaxError of Location.lexing_position + +let from_CST = CST_to_AST.program__to__program + +let parse_file filename = + let open Morbig in + ( + try + Morbig.parse_file filename + with + | Errors.DuringParsing position + | Errors.DuringLexing (position, _) -> + raise (SyntaxError position) + ) + |> from_CST + +let pp_print_safe = SafePrinter.pp_program +let pp_print_debug = AST.pp_program + +module AST = AST + +(* other modules *) + +module Location = Location +module SafePrinter = SafePrinter +module CST_to_AST = CST_to_AST +module Utilities = Morsmall_utilities diff --git a/src/morsmall.mli b/src/morsmall.mli new file mode 100644 index 0000000..20bba5a --- /dev/null +++ b/src/morsmall.mli @@ -0,0 +1,48 @@ +(***************************************************************************) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017,2018,2019 Yann Régis-Gianas, Ralf Treinen, *) +(* Nicolas Jeannerod *) +(* *) +(* 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 . *) +(***************************************************************************) + +module AST = AST +(** Shell AST. *) + +(** {2 Parsers and Converters} *) + +exception SyntaxError of Location.lexing_position + +val from_CST : Morbig.CST.program -> AST.program + +val parse_file : string -> AST.program +(** Parses a whole Shell file into a list of {!AST.command}. The list + can be empty. Can raise {!SyntaxError}. *) + +(** {2 Printers} *) + +val pp_print_safe : Format.formatter -> AST.program -> unit +(** Prints a Shell from its AST. *) + +val pp_print_debug : Format.formatter -> AST.program -> unit +(** Prints a representation of the AST in OCaml-style. *) + +(** {2 Other Modules} *) + +module Location = Location +module SafePrinter = SafePrinter +module CST_to_AST = CST_to_AST +module Utilities = Morsmall_utilities diff --git a/src/safePrinter.ml b/src/safePrinter.ml new file mode 100644 index 0000000..2ca778a --- /dev/null +++ b/src/safePrinter.ml @@ -0,0 +1,274 @@ +(***************************************************************************) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017,2018,2019 Yann Régis-Gianas, Ralf Treinen, *) +(* Nicolas Jeannerod *) +(* *) +(* 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 . *) +(***************************************************************************) + +let fpf = Format.fprintf +open AST + +(* AST.name *) + +let rec pp_name ppf = + fpf ppf "%s" + +(* AST.word_component *) + +and pp_word_component ppf = function (*FIXME*) + | WLiteral literal -> + fpf ppf "%s" literal + | WTildePrefix _ -> + assert false + | WDoubleQuoted _word -> + assert false + | WVariable (variable, attribute) -> + assert (attribute = NoAttribute); + fpf ppf "${%s}" variable + | WSubshell command_list -> + fpf ppf "$(%a)" pp_command'_list command_list + | WGlobAll -> + fpf ppf "*" + | WGlobAny -> + fpf ppf "?" + | WBracketExpression _bracket_expression -> + assert false + +(* AST.word *) + +and pp_word ppf = function + | [] -> assert false + | [e] -> pp_word_component ppf e + | h :: q -> fpf ppf "%a%a" pp_word_component h pp_word q + +and pp_word' ppf word' = + Location.on_located (pp_word ppf) word' + +and pp_words ppf = function + | [] -> () + | [word] -> + pp_word ppf word + | word :: words -> + fpf ppf "%a %a" + pp_word word + pp_words words + +and pp_words' ppf = function + | [] -> () + | [word'] -> + pp_word' ppf word' + | word' :: words' -> + fpf ppf "%a %a" + pp_word' word' + pp_words' words' + +(* AST.pattern *) + +and pp_pattern ppf = function + | [] -> () + | [word] -> + pp_word ppf word + | word :: pattern -> + fpf ppf "%a|%a" + pp_word word + pp_pattern pattern + +and pp_pattern' ppf pattern' = + Location.on_located (pp_pattern ppf) pattern' + +(* AST.assignement *) + +and pp_assignment ppf (variable, word) = + fpf ppf "%a=%a" + pp_name variable + pp_word word + +and pp_assignment' ppf assignment' = + Location.on_located (pp_assignment ppf) assignment' + +and pp_assignments ppf = function + | [] -> () + | [assignment] -> + pp_assignment ppf assignment + | assignment :: assignments -> + fpf ppf "%a %a" + pp_assignment assignment + pp_assignments assignments + +and pp_assignments' ppf = function + | [] -> () + | [assignment'] -> + pp_assignment' ppf assignment' + | assignment' :: assignments' -> + fpf ppf "%a %a" + pp_assignment' assignment' + pp_assignments' assignments' + +and pp_redirection_kind ppf k = + fpf ppf "%s" + (match k with + | Input -> "<" | InputDuplicate -> "<&" + | Output -> ">" | OutputDuplicate -> ">&" | OutputAppend -> ">>" + | InputOutput -> "<>" | OutputClobber -> ">|") + +(* AST.program *) + +and pp_program ppf = function + | [] -> () + | [command'] -> + pp_command' ppf command' + | command' :: program -> + fpf ppf "%a@\n%a" + pp_command' command' + pp_program program + +(* AST.command *) + +and pp_command ppf (command : command) = + fpf ppf "{ "; + ( + match command with + + | Async command -> + pp_command ppf command + + | Seq (command1, command2) -> + fpf ppf "%a;%a" + pp_command' command1 + pp_command' command2 + + | And (command1, command2) -> + fpf ppf "%a&&%a" + pp_command' command1 + pp_command' command2 + + | Or (command1, command2) -> + fpf ppf "%a||%a" + pp_command' command1 + pp_command' command2 + + | Not command -> + fpf ppf "! %a" + pp_command' command + + | Pipe (command1, command2) -> + fpf ppf "%a|%a" + pp_command' command1 + pp_command' command2 + + | Subshell command -> + fpf ppf "(%a)" + pp_command' command + + | If (test, body, None) -> + fpf ppf "if %a;then %a;fi" + pp_command' test + pp_command' body + + | If (test, body, Some rest) -> + fpf ppf "if %a;then %a;else %a;fi" + pp_command' test + pp_command' body + pp_command' rest + + | For (variable, None, body) -> + fpf ppf "for %a;do %a;done" + pp_name variable + pp_command' body + + | For (variable, Some words, body) -> + fpf ppf "for %a in %a;do %a;done" + pp_name variable + pp_words words + pp_command' body + + | Case (word, items) -> + fpf ppf "case %a in" pp_word word; + List.iter + (fun item -> + match item.Location.value with + | (pattern, None) -> + fpf ppf " %a) ;;" pp_pattern' pattern + | (pattern, Some body') -> + fpf ppf " %a) %a;;" pp_pattern' pattern pp_command' body') + items; + fpf ppf " esac" + + | While (test, body) -> + fpf ppf "while %a;do %a;done" + pp_command' test + pp_command' body + + | Until (test, body) -> + fpf ppf "until %a;do %a;done" + pp_command' test + pp_command' body + + | Function (name, body) -> + fpf ppf "%a()%a" + pp_name name + pp_command' body + + | Simple ([], []) -> + failwith "SafePrinter.pp_command': ill-formed command: Simple([], [])" + | Simple ([], words) -> + fpf ppf "%a" pp_words' words + | Simple (assignments, words) -> + fpf ppf "%a %a" + pp_assignments' assignments + pp_words' words + + | Redirection (command, descr, kind, file) -> + (* The space is required because "the [descriptor] must be delimited from any preceding text". *) + fpf ppf "%a %d%a%a" + pp_command' command + descr + pp_redirection_kind kind + pp_word file + + | HereDocument (command, descr, content) -> + (* if content.value.[String.length content.value - 1] <> '\n' then + * failwith "SafePrinter.pp_command': ill-formed here-document: the content must end with a newline"; *) (*FIXME*) + let eof = "EOF" in (*FIXME*) + fpf ppf "%a %d<<%s\n%a%s\n" + pp_command' command + descr + eof + pp_word' content + eof + ); + fpf ppf "%s}" (match command with Async _ -> "&" | HereDocument _ -> "" | _ -> ";") + +and pp_command' ppf command' = + Location.on_located (pp_command ppf) command' + +and pp_command_list ppf = function + | [] -> () + | [command] -> + pp_command ppf command + | command :: command_list -> + fpf ppf "%a@\n%a" + pp_command command + pp_command_list command_list + +and pp_command'_list ppf = function + | [] -> () + | [command'] -> pp_command' ppf command' + | command' :: command'_list -> + fpf ppf "%a@\n%a" + pp_command' command' + pp_command'_list command'_list diff --git a/src/utilities/dune b/src/utilities/dune new file mode 100644 index 0000000..ce2c816 --- /dev/null +++ b/src/utilities/dune @@ -0,0 +1,4 @@ +(library + (name morsmall_utilities) + (public_name morsmall.utilities) + (libraries morbig)) diff --git a/src/utilities/testParser.ml b/src/utilities/testParser.ml new file mode 100644 index 0000000..deae0bd --- /dev/null +++ b/src/utilities/testParser.ml @@ -0,0 +1,244 @@ +(***************************************************************************) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017,2018,2019 Yann Régis-Gianas, Ralf Treinen, *) +(* Nicolas Jeannerod *) +(* *) +(* 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 . *) +(***************************************************************************) + +(** abstract syntax of test expressions *) + +type expression = + | And of expression * expression + | Or of expression * expression + | Not of expression + | Binary of string * string * string (* (op,arg_left,arg_right) *) + | Unary of string * string (* (op,arg) *) + | Single of string (* arg *) + +exception Parse_error + +type token = + | UnOp of string (* unary operators -e, -f, etc. *) + | BinOp of string (* binary operators -eq, =, etc. *) + | AndOp (* -a *) + | OrOp (* -o *) + | NotOp (* ! *) + | ParL (* ( *) + | ParR (* ) *) + | BracketR (* ] *) + | String of string (* all the rest *) + | EOF + +let to_token s = match s with + (* file existence and type *) + | "-e" | "-d" | "-f" | "-b" | "-c" | "-h" | "-L" | "-p" | "-S" -> UnOp s + (* file attributes *) + | "-g" | "-u" | "-s" | "-r" | "-w" | "-x" -> UnOp s + (* GNU extension on files *) + | "-G" | "-O" | "-k" -> UnOp s + (* GNU extension on files *) + | "-nt" | "-ot" | "-ef" -> BinOp s + (* unary operators on strings *) + | "-n" | "-z" -> UnOp s + (* binary operators on strings *) + | "=" | "!=" -> BinOp s + (* binary operators on integers *) + | "-eq" | "-ne" | "-gt" | "-ge" | "-lt" | "-le" -> BinOp s + (* unary operator on file descriptor *) + | "-t" -> UnOp s + | "-a" -> AndOp + | "-o" -> OrOp + | "(" -> ParL + | ")" -> ParR + | "]" -> BracketR + | "!" -> NotOp + | _ -> String s + +let parse ?(bracket=false) wl = + let tokenbuf = + wl + |> List.map Morbig.remove_quotes + |> List.map to_token + |> ref + in + let lookup () = + match !tokenbuf with + | h::_ -> h + | [] -> EOF + in + let pop () = + match !tokenbuf with + | _::r -> tokenbuf := r + | [] -> assert false + in + + let rec parse_S () = + let exp = parse_S' () in + if bracket then + if lookup () = BracketR then + pop () + else + raise Parse_error; + if lookup () = EOF then + exp + else + raise Parse_error + + and parse_S' () = + match lookup () with + | EOF | BracketR -> None + | _ -> Some (parse_disj ()) + + and parse_disj () = + let head = parse_conj () in + match parse_disj' () with + | None -> head + | Some rest -> Or (head,rest) + + and parse_disj' () = + match lookup () with + | EOF | BracketR | ParR -> None + | OrOp -> pop (); Some (parse_disj ()) + | _ -> raise Parse_error + + and parse_conj () = + let head = parse_literal () in + match parse_conj' () with + | None -> head + | Some rest -> And (head, rest) + + and parse_conj' () = + match lookup () with + | OrOp | EOF | BracketR | ParR -> None + | AndOp -> pop (); Some (parse_conj ()) + | _ -> raise Parse_error + + and parse_literal () = + match lookup () with + | NotOp -> pop (); Not (parse_atom ()) + | UnOp _ | ParL | String _ -> parse_atom () + | _ -> raise Parse_error + + and parse_atom () = + match lookup () with + | UnOp op -> + pop (); + (match lookup () with + | String s -> pop (); Unary (op,s) + | _ -> raise Parse_error) + | ParL -> + pop (); + let exp = parse_disj () in + (match lookup () with + | ParR -> pop (); exp + | _ -> raise Parse_error) + | String s -> + pop (); + (match parse_atom' () with + | None -> Single s + | Some (binop,rightarg) -> Binary (binop,s,rightarg)) + | _ -> raise Parse_error + + and parse_atom' () = + match lookup () with + | AndOp | OrOp | EOF | BracketR -> None + | BinOp binop -> + pop (); + (match lookup () with + | String rightarg | UnOp rightarg | BinOp rightarg + -> pop (); Some (binop,rightarg) + | _ -> raise Parse_error) + | _ -> raise Parse_error + in + + parse_S () + + +(* + +grammar of test expressions: + + -> EOF | EOF + -> | -o + -> | -a + -> | ! + -> string | unop string | string binop string | ( ) + +grammar in LL(1): + + -> EOF + -> EPSILON | + -> + -> EPSILON | -o + -> + -> EPSILON | -a + -> | ! + -> string | unop string | ( ) + -> EPSILON | binop string + +annulating non-terminals: { , , } + +nonterminal | Fi_1 +------------+-------------------- + | string, unop, (, ! + | string, unop, (, ! + | -o + | string, unop, (, ! + | -a + | string, unop, (, ! + | string, unop, ( + | binop + +right side | FIRST_1 +-------------------+--------------------- + EOF | string, unop, (, ! + | string, unop, (, ! +-o | -o + | string, unop, (, ! +-a | -a + | string, unop, ( +! | ! +string | string +unop string | unop +( ) | ( +binop string | binop + +nonterminal | FOLLOW_1 +------------+-------------------- + | \emptyset + | EOF, ) + | EOF, ) + | -o, EOF, ) + | -o, EOF, ) + | -a, -o, EOF, ) + | -a, -o, EOF, ) + | -a, -o, EOF, ) + +Hence we have the following requirements for being LL(1): + +nonterminal | must be mutually disjoint +------------+-------------------------- + | --- + | --- + | EOF, ), -o + | --- + | -o, EOF, ), -a + | string, unop, (, ! + | string, unop, ( + | -a, -o, EOF, ), binop + +*) diff --git a/src/utilities/testParser.mli b/src/utilities/testParser.mli new file mode 100644 index 0000000..bee7386 --- /dev/null +++ b/src/utilities/testParser.mli @@ -0,0 +1,37 @@ +(***************************************************************************) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017,2018,2019 Yann Régis-Gianas, Ralf Treinen, *) +(* Nicolas Jeannerod *) +(* *) +(* 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 . *) +(***************************************************************************) + +(** abstract syntax of test expressions *) + +type expression = + | And of expression * expression + | Or of expression * expression + | Not of expression + | Binary of string * string * string (* (op,arg_left,arg_right) *) + | Unary of string * string (* (op,arg) *) + | Single of string (* arg *) + +exception Parse_error + +(** [parse ~bracket wl] parses the list of words [wl] as a test + expression (or [None] if [wl] is empty). If [bracket] is [true] + then the last word of [wl] must be a right bracket. *) +val parse: ?bracket:bool -> string list -> expression option diff --git a/tests/dune b/tests/dune new file mode 100644 index 0000000..ea5cb4f --- /dev/null +++ b/tests/dune @@ -0,0 +1,4 @@ +(executable + (name run) + (libraries ppx_deriving_yojson.runtime morbig morsmall) + (flags :standard -w +A-42)) diff --git a/tests/generator.ml b/tests/generator.ml new file mode 100644 index 0000000..dc3d5fa --- /dev/null +++ b/tests/generator.ml @@ -0,0 +1,231 @@ +(******************************************************************************) +(* *) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017 Yann Régis-Gianas, Ralf Treinen, Nicolas Jeannerod *) +(* *) +(* 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 . *) +(* *) +(******************************************************************************) + +open Morsmall.AST +open Morsmall.Location + +let dummy_lexing_position = + { pos_fname = "dummy" ; + pos_lnum = 0 ; + pos_bol = 0 ; + pos_cnum = 0 } + +let dummy_locate f x = + { value = f x ; + position = { start_p = dummy_lexing_position ; + end_p = dummy_lexing_position } } + +type 'a p_array = (int * 'a) array + +let choose (a : 'a p_array) : 'a = + let p_max = Array.fold_left (fun p_tot (p,_) -> p_tot+p) 0 a in + let n = Random.int p_max in + let p_tot = ref 0 in + let v_found = ref (snd (a.(0))) in + for i = 0 to Array.length a - 1 do + let (p, v) = a.(i) in + if !p_tot <= n && n < !p_tot + p then + v_found := v; + p_tot := !p_tot + p + done; + !v_found + +(* Parameters *) + +type parameters = + { depth : int } + +let default_parameters = + { depth = 10 } + +let d p = { depth = p.depth - 1 } (* { p with depth = p.depth - 1 } *) + +(* Generator helper functions *) + +(* let g_bool ~prob = + * Random.float 1. < prob *) + +let g_option ~prob inhabitant = + if Random.float 1. < prob then + Some (inhabitant ()) + else + None + +let rec g_list ~prob ~limit inhabitant = + if limit > 0 && Random.float 1. < prob then + (inhabitant ()) :: g_list ~prob ~limit:(limit - 1) inhabitant + else + [] + +(* Our generators *) + +let rec g_word_component p : word_component = + choose + [| 1, (fun _ -> Literal "foo") ; + 1, (fun _ -> Variable ("x", NoAttribute)) ; + (if p.depth <= 0 then 0 else 1), + (fun p -> Subshell (g_program p)) ; + 1, (fun _ -> GlobAll) ; + 1, (fun _ -> GlobAny) |] + (d p) + +and g_word p = + g_word_component (d p) + :: g_list ~prob:0.9 ~limit:4 (fun () -> g_word_component (d p)) + +and g_word' p = + dummy_locate g_word p + +and g_name _p = + "blah" (*FIXME*) + +and g_pattern p = + g_word (d p) :: g_list ~prob:0.8 ~limit:4 (fun () -> g_word (d p)) + +and g_pattern' p = + dummy_locate g_pattern p + +and g_assignment p = + (choose [|1,"x";2,"y";3,"z";4,"choucroute"|], + g_word (d p)) + +and g_assignment' p = + dummy_locate g_assignment p + +and g_descr _p = + Random.int 10 + +and g_redirection_kind _p = + choose + [| 1, Output ; + 1, OutputDuplicate ; + 1, OutputAppend ; + 1, OutputClobber ; + 1, Input ; + 1, InputDuplicate ; + 1, InputOutput |] + +and g_program p = + g_list ~prob:0.5 ~limit:3 + (fun () -> g_command' (d p)) + +and g_command p = + if p.depth <= 0 then + g_simple_command (d p) + else + choose + [| 1, g_simple_command ; + 1, (fun p -> Async (g_command (d p))) ; + 1, (fun p -> Seq (g_command' (d p), g_command' (d p))) ; + 1, (fun p -> And (g_command' (d p), g_command' (d p))) ; + 1, (fun p -> Or (g_command' (d p), g_command' (d p))) ; + 1, (fun p -> Not (g_command' (d p))) ; + 1, (fun p -> Pipe (g_command' (d p), g_command' (d p))) ; + 1, (fun p -> Subshell (g_command' (d p))) ; + 1, g_for_clause ; + 1, g_case_clause ; + 1, g_if_clause ; + 1, g_while_clause ; + 1, g_until_clause ; + 1, g_function_definition ; + 1, g_redirection ; + 1, g_here_document |] + (d p) + +and g_command' p = + dummy_locate g_command p + +and g_simple_command p = + let assignments = + g_list ~prob:0.5 ~limit:5 + (fun () -> g_assignment' (d p)) + in + let words = + g_list ~prob:0.7 ~limit:10 + (fun () -> g_word' (d p)) + in + if assignments = [] && words = [] then + g_simple_command p + else + Simple (assignments, words) + +and g_for_clause p = + For ( + "x", + g_option ~prob:0.8 (fun () -> g_list ~prob:0.8 ~limit:10 (fun () -> g_word (d p))), + g_command' (d p) + ) + +and g_case_clause p = + Case ( + g_word (d p), + g_list ~prob:0.7 ~limit:5 (fun () -> g_case_item' (d p) ) + ) + +and g_case_item p = + ( + g_pattern' (d p), + g_option ~prob:0.9 (fun () -> g_command' (d p)) + ) + +and g_case_item' p = + dummy_locate g_case_item p + +and g_if_clause p = + If ( + g_command' (d p), + g_command' (d p), + g_option ~prob:0.6 (fun () -> g_command' (d p)) + ) + +and g_while_clause p = + While ( + g_command' (d p), + g_command' (d p) + ) + +and g_until_clause p = + Until ( + g_command' (d p), + g_command' (d p) + ) + +and g_function_definition p = + Function ( + g_name (d p), + g_command' (d p) + ) + +and g_redirection p = + Redirection ( + g_command' (d p), + g_descr (d p), + g_redirection_kind (d p), + g_word (d p) + ) + +and g_here_document p = + HereDocument ( + g_command' (d p), + g_descr (d p), + dummily_located (g_word (d p) @ [Literal "\n"]) + ) diff --git a/tests/generator.mli b/tests/generator.mli new file mode 100644 index 0000000..57c4d7a --- /dev/null +++ b/tests/generator.mli @@ -0,0 +1,28 @@ +(******************************************************************************) +(* *) +(* Morsmall *) +(* A concise AST for POSIX shell *) +(* *) +(* Copyright (C) 2017 Yann Régis-Gianas, Ralf Treinen, Nicolas Jeannerod *) +(* *) +(* 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 . *) +(* *) +(******************************************************************************) + +type parameters = + { depth : int } + +val default_parameters : parameters + +val g_program : parameters -> Morsmall.AST.program diff --git a/tests/run.ml b/tests/run.ml new file mode 100644 index 0000000..db31969 --- /dev/null +++ b/tests/run.ml @@ -0,0 +1,117 @@ + +exception CouldntParse of Morsmall.AST.program +exception ASTsDontMatch of Morsmall.AST.program * Morsmall.AST.program + +let generator_parameters = Generator.default_parameters + +let number_of_tests = 100 + +(* *) + +let run_one_test () = + (* Create a temporary file *) + let (filename, out_channel) = Filename.open_temp_file "morsmall_test_" ".sh" in + let formatter = Format.formatter_of_out_channel out_channel in + + (* Create a random script, put it in the file *) + let ast = Generator.(g_program generator_parameters) in + Morsmall.pp_print_safe formatter ast; + + (* Close the file *) + Format.fprintf formatter "@."; + close_out out_channel; + + try + ( + (* Parse the file with Morbig and Morsmall *) + let ast' = + try + Morsmall.parse_file filename + with + Morsmall.SyntaxError _pos -> + raise (CouldntParse ast) + in + + (* Compare *) + if not (Morsmall.AST.equal_program ast ast') then + raise (ASTsDontMatch (ast, ast')) + ); + + (* Clean the temporary file *) + Sys.remove filename + with + | _ as exn -> + Sys.remove filename; + raise exn + +let () = + let errors = ref 0 in + + for i = 1 to number_of_tests do + Format.printf "Running test #%d...\r@?" i; + try + run_one_test () + with + | _ as exn -> + ( + (* Generate a report *) + + let filename = "morsmall_test_report_"^(string_of_int i)^".org" in + let out_channel = open_out filename in + let formatter = Format.formatter_of_out_channel out_channel in + Format.fprintf formatter "#+TITLE: Morsmall Test Engine -- Report on Test #%d\n\n" i; + Format.fprintf formatter "* The Error\n"; + let ast = + ( + match exn with + | CouldntParse ast -> + Format.fprintf formatter "Morbig could not parse the file produced by Morsmall's printer.\n"; + ast + + | ASTsDontMatch (ast, _) -> + Format.fprintf formatter "The parsed AST does not coincide with the generated one.\n"; + ast + + | _ as exn -> raise exn + ) + in + Format.fprintf formatter "* Generated AST\n%a\n" Morsmall.pp_print_debug ast; + Format.fprintf formatter "* Generated Shell Script\n%a\n" Morsmall.pp_print_safe ast; + ( + match exn with + | ASTsDontMatch (_, ast') -> + ( + Format.fprintf formatter + "* Parsed AST\n%a\n" + Morsmall.pp_print_debug ast'; + + try + Format.fprintf formatter + "* Parsed Shell Script\n%a\n" + Morsmall.pp_print_safe ast' + with + Assert_failure _ -> + Format.fprintf formatter "* Error while printing the parsed AST@."; + Printexc.print_backtrace out_channel + ) + | _ -> () + ); + Format.fprintf formatter "@?"; + close_out out_channel; + + (* Complain *) + Format.eprintf "Error in test #%d: check report in '%s'\n" i filename; + incr errors + ) + done; + + if !errors = 0 then + ( + Format.printf "Successfully ran %d tests.@." number_of_tests; + exit 0 + ) + else + ( + Format.printf "While running %d tests, got %d errors. See the reports for more details.@." number_of_tests !errors; + exit 1 + ) -- cgit v1.2.3