packages feed

polyglot (empty) → 0.1.1.0

raw patch · 54 files changed

+5844/−0 lines, 54 filesdep +basedep +bookhounddep +bytestring

Dependencies added: base, bookhound, bytestring, casing, containers, directory, directory-tree, extra, filepath, fsnotify, optparse-applicative, parallel, polyglot, text, utility-ht

Files

+ LICENSE view
@@ -0,0 +1,674 @@+                    GNU GENERAL PUBLIC LICENSE+                       Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++                            Preamble++  The GNU General Public License is a free, copyleft license for+software and other kinds of works.++  The licenses for most software and other practical works are designed+to take away your freedom to share and change the works.  By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.  We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors.  You can apply it to+your programs, too.++  When we speak of free software, we are referring to freedom, not+price.  Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++  To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights.  Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++  For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received.  You must make sure that they, too, receive+or can get the source code.  And you must show them these terms so they+know their rights.++  Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++  For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software.  For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++  Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so.  This is fundamentally incompatible with the aim of+protecting users' freedom to change the software.  The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable.  Therefore, we+have designed this version of the GPL to prohibit the practice for those+products.  If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++  Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary.  To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++  The precise terms and conditions for copying, distribution and+modification follow.++                       TERMS AND CONDITIONS++  0. Definitions.++  "This License" refers to version 3 of the GNU General Public License.++  "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++  "The Program" refers to any copyrightable work licensed under this+License.  Each licensee is addressed as "you".  "Licensees" and+"recipients" may be individuals or organizations.++  To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy.  The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++  A "covered work" means either the unmodified Program or a work based+on the Program.++  To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy.  Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++  To "convey" a work means any kind of propagation that enables other+parties to make or receive copies.  Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++  An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License.  If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++  1. Source Code.++  The "source code" for a work means the preferred form of the work+for making modifications to it.  "Object code" means any non-source+form of a work.++  A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++  The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form.  A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++  The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities.  However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work.  For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++  The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++  The Corresponding Source for a work in source code form is that+same work.++  2. Basic Permissions.++  All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met.  This License explicitly affirms your unlimited+permission to run the unmodified Program.  The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work.  This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++  You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force.  You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright.  Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++  Conveying under any other circumstances is permitted solely under+the conditions stated below.  Sublicensing is not allowed; section 10+makes it unnecessary.++  3. Protecting Users' Legal Rights From Anti-Circumvention Law.++  No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++  When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++  4. Conveying Verbatim Copies.++  You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++  You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++  5. Conveying Modified Source Versions.++  You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++    a) The work must carry prominent notices stating that you modified+    it, and giving a relevant date.++    b) The work must carry prominent notices stating that it is+    released under this License and any conditions added under section+    7.  This requirement modifies the requirement in section 4 to+    "keep intact all notices".++    c) You must license the entire work, as a whole, under this+    License to anyone who comes into possession of a copy.  This+    License will therefore apply, along with any applicable section 7+    additional terms, to the whole of the work, and all its parts,+    regardless of how they are packaged.  This License gives no+    permission to license the work in any other way, but it does not+    invalidate such permission if you have separately received it.++    d) If the work has interactive user interfaces, each must display+    Appropriate Legal Notices; however, if the Program has interactive+    interfaces that do not display Appropriate Legal Notices, your+    work need not make them do so.++  A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit.  Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++  6. Conveying Non-Source Forms.++  You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++    a) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by the+    Corresponding Source fixed on a durable physical medium+    customarily used for software interchange.++    b) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by a+    written offer, valid for at least three years and valid for as+    long as you offer spare parts or customer support for that product+    model, to give anyone who possesses the object code either (1) a+    copy of the Corresponding Source for all the software in the+    product that is covered by this License, on a durable physical+    medium customarily used for software interchange, for a price no+    more than your reasonable cost of physically performing this+    conveying of source, or (2) access to copy the+    Corresponding Source from a network server at no charge.++    c) Convey individual copies of the object code with a copy of the+    written offer to provide the Corresponding Source.  This+    alternative is allowed only occasionally and noncommercially, and+    only if you received the object code with such an offer, in accord+    with subsection 6b.++    d) Convey the object code by offering access from a designated+    place (gratis or for a charge), and offer equivalent access to the+    Corresponding Source in the same way through the same place at no+    further charge.  You need not require recipients to copy the+    Corresponding Source along with the object code.  If the place to+    copy the object code is a network server, the Corresponding Source+    may be on a different server (operated by you or a third party)+    that supports equivalent copying facilities, provided you maintain+    clear directions next to the object code saying where to find the+    Corresponding Source.  Regardless of what server hosts the+    Corresponding Source, you remain obligated to ensure that it is+    available for as long as needed to satisfy these requirements.++    e) Convey the object code using peer-to-peer transmission, provided+    you inform other peers where the object code and Corresponding+    Source of the work are being offered to the general public at no+    charge under subsection 6d.++  A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++  A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling.  In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage.  For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product.  A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++  "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source.  The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++  If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information.  But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++  The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed.  Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++  Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++  7. Additional Terms.++  "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law.  If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++  When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it.  (Additional permissions may be written to require their own+removal in certain cases when you modify the work.)  You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++  Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++    a) Disclaiming warranty or limiting liability differently from the+    terms of sections 15 and 16 of this License; or++    b) Requiring preservation of specified reasonable legal notices or+    author attributions in that material or in the Appropriate Legal+    Notices displayed by works containing it; or++    c) Prohibiting misrepresentation of the origin of that material, or+    requiring that modified versions of such material be marked in+    reasonable ways as different from the original version; or++    d) Limiting the use for publicity purposes of names of licensors or+    authors of the material; or++    e) Declining to grant rights under trademark law for use of some+    trade names, trademarks, or service marks; or++    f) Requiring indemnification of licensors and authors of that+    material by anyone who conveys the material (or modified versions of+    it) with contractual assumptions of liability to the recipient, for+    any liability that these contractual assumptions directly impose on+    those licensors and authors.++  All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10.  If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term.  If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++  If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++  Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++  8. Termination.++  You may not propagate or modify a covered work except as expressly+provided under this License.  Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++  However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++  Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++  Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License.  If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++  9. Acceptance Not Required for Having Copies.++  You are not required to accept this License in order to receive or+run a copy of the Program.  Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance.  However,+nothing other than this License grants you permission to propagate or+modify any covered work.  These actions infringe copyright if you do+not accept this License.  Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++  10. Automatic Licensing of Downstream Recipients.++  Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License.  You are not responsible+for enforcing compliance by third parties with this License.++  An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations.  If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++  You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License.  For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++  11. Patents.++  A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based.  The+work thus licensed is called the contributor's "contributor version".++  A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version.  For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++  Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++  In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement).  To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++  If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients.  "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++  If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++  A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License.  You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++  Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++  12. No Surrender of Others' Freedom.++  If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License.  If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all.  For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++  13. Use with the GNU Affero General Public License.++  Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work.  The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++  14. Revised Versions of this License.++  The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time.  Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++  Each version is given a distinguishing version number.  If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation.  If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++  If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++  Later license versions may give you additional or different+permissions.  However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++  15. Disclaimer of Warranty.++  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++  16. Limitation of Liability.++  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++  17. Interpretation of Sections 15 and 16.++  If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++                     END OF TERMS AND CONDITIONS++            How to Apply These Terms to Your New Programs++  If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++  To do so, attach the following notices to the program.  It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++    <one line to give the program's name and a brief idea of what it does.>+    Copyright (C) <year>  <name of author>++    This program is free software: you can redistribute it and/or modify+    it under the terms of the GNU General Public License as published by+    the Free Software Foundation, either version 3 of the License, or+    (at your option) any later version.++    This program is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program.  If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++  If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++    <program>  Copyright (C) <year>  <name of author>+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+    This is free software, and you are welcome to redistribute it+    under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License.  Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++  You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<https://www.gnu.org/licenses/>.++  The GNU General Public License does not permit incorporating your program+into proprietary programs.  If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library.  If this is what you want to do, use the GNU Lesser General+Public License instead of this License.  But first, please read+<https://www.gnu.org/licenses/why-not-lgpl.html>.
+ README.md view
@@ -0,0 +1,179 @@+# polyglot++## Description++CLI tool to transpile Haskell modules to several target languages.++The CLI can convert individual Haskell files as well as recursively+convert directory trees (or entire projects).++There are a few options available to, for example, +watch a file / directory and reactively convert it whenever modified,+as well as to format the output target language files.++At the moment, only parsing of Haskell 98 / 2010 standards along with a subset of GHC Syntax Extensions is supported (for example, there is currently no support for either Template Haskell or some of the GHC Syntax Extensions, such as GADTs and Type Families).++## Usage++```+Usage: polyglot (-l|--language ARG) (-i|--input ARG) (-o|--output ARG) +                [-f|--format] [-w|--watch] [--clear]++  Compile Haskell file(s) into a target language.++Available options:+  -h,--help                Show this help text+  -l,--language ARG        Target language+  -i,--input ARG           Path of input Haskell file or directory+  -o,--output ARG          Path of output file or directory+  -f,--format              Apply formatter on output file(s)+  -w,--watch               Watch for changes and convert automatically+  --clear                  Clear the output directory contents before conversion++Supported languages: Purescript, Scala+```++## Details++This CLI tool aims to perform a one-to-one mapping between Haskell and target language constructs.+This can be done in most cases, because all of the available target languages support many of Haskell key features that are not necessarily available in other mainstream languages, such as Higher Kinded Types, Typeclasses, GADTs & Higher Rank Polymorphism.++However, the conversion can be lossy, so some information can be lost in the process. At the same time, it can be necessary to provide some extra information in the target language version of the source file (most prominently (type / kind) signatures, due to less powerful type inference mechanisms than Hindley-Millner in the target language).++The resulting files will have a dependency on some kind of prelude library that will expose all of the usual functions, data types, type classes and instances included in the Haskell prelude.++Also, bear in mind that in some cases due to different call semantics (lazy or call-by-need vs strict) and also runtime support for features (such as tail call optimization), the resulting files in the target language will probably need on some cases to be manually adapted post conversion, to preserve or approximate to the original Haskell code runtime characteristics.++In any case, it can be helpful to check the output files and manually adapt them as desired, because many Haskell idioms may not be the best match in the target language (This can be specially the case for languages that are not in the ML family (such as Scala)). +++## Examples+++Sample Haskell snippet:++```haskell++data Language+  = Purescript+  | Scala+  deriving (Bounded, Enum, Eq, Ord, Show)++parserOption :: Bookhound.Parser a -> Options.Applicative.Mod Options.Applicative.OptionFields a -> Parser a+parserOption parser = option $ eitherReader $ reader+  where+    reader = mapLeft show . Bookhound.runParser parser . pack++```++Converted Purescript output (after formatting):++```purescript++data Language+  = Purescript+  | Scala+derive instance Bounded Language+derive instance Enum Language+derive instance Eq Language+derive instance Ord Language+derive instance Show Language++parserOption :: forall a. Bookhound.Parser a -> Options.Applicative.Mod Options.Applicative.OptionFields a -> Parser a+parserOption parser = option $ eitherReader $ reader+  where+    reader = mapLeft show <<< Bookhound.runParser parser <<< pack++```++Sample Haskell snippet:++```haskell++action :: (ParseError -> IO ()) -> Opts -> IO ()+action errorAction Opts{language, sourcePath, targetPath, autoFormat} =+  readFileUtf8 sourcePath+  >>= (pack <<$>>) . traverse format . toTargetLanguage language+  >>= either errorAction createDirAndWriteFile++  where+    createDirAndWriteFile x = createDirectoryIfMissing True finalDir *>+                              writeFileUtf8 finalPath x+    finalDir                = takeDirectory finalPath+    finalPath               = pathToLanguage language targetPath'++    targetPath' = if isDir targetPath then+                    replaceFileName targetPath (takeFileName sourcePath)+                  else+                    targetPath++    format      = if autoFormat then+                    readProcess (formatterExec language)+                                ["--stdin", finalPath]+                  else+                    pure++```++Converted Scala output (after formatting):++```scala++def action(x: ParseError => IO[Unit])(y: Opts): IO[Unit] =+  (x, y) match+    case (errorAction, Opts(language, sourcePath, targetPath, autoFormat)) =>+      def createDirAndWriteFile =+        createDirectoryIfMissing(true)(finalDir) *> writeFileUtf8(finalPath)(x)+      def finalDir =+        takeDirectory(finalPath)+      def finalPath =+        pathToLanguage(language, targetPath$)+      def targetPath$ =+        if isDir(targetPath) then+          replaceFileName(targetPath)(takeFileName(sourcePath))+        else targetPath+      def format =+        if autoFormat then+          readProcess(formatterExec(language))(List("--stdin", finalPath))+        else pure++      readFileUtf8(sourcePath)+      >>= (pack <<&>> _) ^ traverse(format) ^ toTargetLanguage(language)+      >>= either(errorAction)(createDirAndWriteFile)++```+++## Supported GHC Syntax Extensions++``` yaml++# Syntax Sugar+- LambdaCase+- MultiWayIf+- PostfixOperators++# Types+- RankNTypes+- ExplicitForAll+- ScopedTypeVariables++# Records+- DuplicateRecordFields+- NoFieldSelectors+- NamedFieldPuns+- RecordWildCards+- OverloadedRecordDot++# Type Classes+- ConstrainedClassMethods+- MultiParamTypeClasses++# Deriving +- StandaloneDeriving+- DerivingVia+- NewTypeDeriving+- AnyClassDeriving+- DerivingStrategies++```
+ app/CommandLine/FileIO.hs view
@@ -0,0 +1,144 @@+module CommandLine.FileIO where++import CommandLine.Options (Language (..), Opts (..))++import Lexers.Haskell.Layout (adaptLayout)++import Control.Monad               ((<=<))+import Control.Parallel.Strategies (parMap, rseq)+import Data.List                   (isPrefixOf)+import Data.Text                   (Text, pack)+import Data.Text.Encoding          (decodeUtf8, encodeUtf8)+import Utils.Foldable              (andPred, orPred, wrapMaybe)+import Utils.Functor               ((<<$>>))+import Utils.String                (wrapBlock, wrapContext)+++import System.Directory      (canonicalizePath)+import System.Directory.Tree (AnchoredDirTree (..), DirTree (..))+import System.FilePath       (joinPath, normalise, splitDirectories, splitPath,+                              takeDirectory, takeExtensions, takeFileName,+                              (-<.>), (</>))+import System.FSNotify       (ActionPredicate, Event (..))+++import qualified Data.ByteString as B (readFile, writeFile)++import qualified Conversions.ToPurescript.ModuleDef as ToPurescript+import qualified Conversions.ToScala.ModuleDef      as ToScala+import qualified Parsers.Haskell.ModuleDef          as Parser++import Bookhound.Parser (ParseError, runParser)+import Utils.String     (wrapNewLines)+++toTargetLanguage :: Language -> Text -> Either [ParseError] String+toTargetLanguage language = convert <=< adaptLayout+  where+    convert = syntaxConverter <<$>> runParser Parser.moduleDef+    syntaxConverter = case language of+      Purescript -> show . ToPurescript.moduleDef+      Scala      -> show . ToScala.moduleDef+++convertDirTree :: Language -> DirTree Text -> DirTree Text+convertDirTree language (File x y)+  | isHaskellFile x = applyTransform y+    where+      applyTransform = either (Failed x . userError . wrapNewLines+                              . wrapContext . ("Parse Errors: " ++)+                              . wrapBlock)+                              (File $ pathToLanguage language x)+                       . (pack <$>) . toTargetLanguage language++convertDirTree language (Dir x y) = Dir x (parMap rseq (convertDirTree language) y)+convertDirTree _ x = x+++moveTree :: FilePath -> AnchoredDirTree a -> AnchoredDirTree a+moveTree fp2 (_ :/ x@(Dir _ _)) = "." :/ newDirTree+  where++    newDirTree    = foldr (\curr acc -> Dir curr [acc]) prunedDirTree+                                                      (init outputDirs)+    prunedDirTree = Dir (last outputDirs)+                        (getDirTreeContents 1 x)+    outputDirs = splitDirectories $ takeDirectory $ normalise fp2++moveTree _ x                      = x+++reportFailure :: DirTree a -> IO ()+reportFailure (Failed x y) = putStrLn $+  "\nFailure when converting file " ++ x ++ ": " ++ show y+reportFailure _ = pure ()+++watchPred :: Foldable t => t FilePath -> ActionPredicate+watchPred x (Added fp _ _)    = filePathPred fp x+watchPred x (Modified fp _ _) = filePathPred fp x+watchPred x (Removed fp _ _)  = filePathPred fp x+watchPred _ _                 = False+++filePathPred :: Foldable t => FilePath -> t FilePath -> Bool+filePathPred fp x = isHaskellFile fp+                    && all (== fileName) x+  where+    fileName = takeFileName fp++getWatchPath :: FilePath -> Opts -> IO FilePath+getWatchPath fp Opts{sourcePath, targetPath} =+  maybe targetPath (targetPath </>) . wrapMaybe <$> prunedPath+  where+    prunedPath          = diffPath <$> traverse canonicalizePath (fp, sourcePath)+    diffPath (fp1, fp2) = joinPath $ drop (length $ splitPath fp2)+                                          (splitPath fp1)+++getDirTreeContents :: Int -> DirTree a -> [DirTree a]+getDirTreeContents n (Dir _ x)+  | n > 0 = x  >>= getDirTreeContents (n - 1)+getDirTreeContents _ x = [x]+++isDir :: FilePath -> Bool+isDir = null . takeFileName++isHaskellFile :: FilePath -> Bool+isHaskellFile = (`elem` [".hs", ".lhs"]) . takeExtensions++isDotFile :: String -> Bool+isDotFile = andPred [isPrefixOf ".", (/= "."), (/= "..")]+++pathToLanguage :: Language -> FilePath -> FilePath+pathToLanguage language = (-<.> extension)+  where+    extension = case language of+      Purescript -> "purs"+      Scala      -> "scala"++formatterExec :: Language -> FilePath+formatterExec Purescript = "purs-tidy"+formatterExec Scala      = "scalafmt"++emitError :: [ParseError] -> IO ()+emitError = fail . ("\n\nParse Errors: " ++) . wrapBlock+++dirNamePred :: String -> Bool+dirNamePred = not . orPred [isDotFile, (== "bin")]++dirPred :: DirTree a -> Bool+dirPred (Dir x _) = dirNamePred x+dirPred _         = True+++readFileUtf8 :: FilePath -> IO Text+readFileUtf8 fp | all dirNamePred (splitDirectories fp)+  = decodeUtf8 <$> B.readFile fp+readFileUtf8 _ = pure mempty++writeFileUtf8 :: FilePath -> Text -> IO ()+writeFileUtf8 fp = B.writeFile fp . encodeUtf8
+ app/CommandLine/Options.hs view
@@ -0,0 +1,73 @@+module CommandLine.Options where++import Data.Either.Extra   (mapLeft)+import Data.List           (intercalate)+import Data.Text           (pack)+import Options.Applicative hiding ((<|>))++import qualified Bookhound.Parser            as Bookhound+import           Bookhound.ParserCombinators++++opts :: Parser Opts+opts = Opts+    <$> parserOption language+        ( long "language"+        <> short 'l'+        <> help "Target language")+    <*> strOption+        ( long "input"+        <> short 'i'+        <> help "Path of input Haskell file or directory" )+    <*> strOption+        ( long "output"+        <> short 'o'+        <> help "Path of output file or directory" )+    <*> switch+        ( long "format"+        <> short 'f'+        <> help "Apply formatter on output file(s)" )+    <*> switch+        ( long "watch"+        <> short 'w'+        <> help "Watch for changes and convert automatically" )+    <*> switch+        ( long "clear"+        <> help "Clear the output directory contents before conversion" )++optsInfo :: ParserInfo Opts+optsInfo = info (helper <*> opts)+           ( fullDesc+           <> progDesc "Compile Haskell file(s) into a target language. \n"+           <> footer ("Supported languages: "+            <> (intercalate ", " $ show <$> ([minBound .. maxBound] :: [Language])))+           <> header "polyglot" )+++data Opts+  = Opts+      { language      :: Language+      , sourcePath    :: FilePath+      , targetPath    :: FilePath+      , autoFormat    :: Bool+      , watchMode     :: Bool+      , clearContents :: Bool+      }++data Language+  = Purescript+  | Scala+  deriving (Bounded, Enum, Eq, Ord, Show)+++language :: Bookhound.Parser Language+language = Purescript <$ oneOf ["Purescript", "purescript", "purs"] <|>+           Scala      <$ oneOf ["Scala", "scala"]++++parserOption :: Bookhound.Parser a -> Options.Applicative.Mod Options.Applicative.OptionFields a -> Parser a+parserOption parser = option $ eitherReader $ reader+  where+    reader = mapLeft show . Bookhound.runParser parser . pack
+ app/CommandLine/Process.hs view
@@ -0,0 +1,116 @@+module CommandLine.Process where+++import CommandLine.FileIO  (convertDirTree, dirPred, emitError, formatterExec,+                            getWatchPath, isDir, moveTree, pathToLanguage,+                            readFileUtf8, reportFailure, toTargetLanguage,+                            watchPred, writeFileUtf8)+import CommandLine.Options (Opts (..))+++import Control.Concurrent  (threadDelay)+import Control.Monad       (forever, when)+import Control.Monad.Extra (andM, whenM)+import Data.Foldable       (traverse_)+import Data.Text           (pack)+import Utils.Foldable      (wrapMaybe)+import Utils.Functor       ((<<$>>))+++import System.Directory.Extra (createDirectoryIfMissing, doesDirectoryExist,+                               getHomeDirectory, removeDirectoryRecursive,+                               removeFile)+import System.Directory.Tree  (AnchoredDirTree (..), failures, filterDir,+                               readDirectoryWith, writeDirectoryWith, (</$>))+import System.FilePath        (equalFilePath, replaceFileName, takeDirectory,+                               takeFileName)+import System.FSNotify        (Action, Event (..), watchTree, withManager)+import System.Process.Extra   (callProcess, readProcess)++import Bookhound.Parser (ParseError)+++process :: Opts -> FilePath -> IO ()+process opts@Opts{watchMode, sourcePath, targetPath} homeDir+  | any (equalFilePath homeDir) [sourcePath, targetPath] =+      fail "Neither source nor target paths can be the home directory"+  | isDir sourcePath && not (isDir targetPath) =+      fail "If the input path is a directory then the output path must be a directory as well"+  | equalFilePath sourcePath targetPath =+      fail "The output path cannot be the same as the input path"+  | watchMode                      = watchPath opts+  | null (takeFileName sourcePath)    = actions opts+  | otherwise                      = action emitError opts++++action :: ([ParseError] -> IO ()) -> Opts -> IO ()+action errorAction Opts{language, sourcePath, targetPath, autoFormat} =+  readFileUtf8 sourcePath+  >>= (pack <<$>>) . traverse format . toTargetLanguage language+  >>= either errorAction createDirAndWriteFile++  where+    createDirAndWriteFile x = createDirectoryIfMissing True finalDir *>+                              writeFileUtf8 finalPath x+    finalDir                = takeDirectory finalPath+    finalPath               = pathToLanguage language targetPath'++    targetPath' = if isDir targetPath then+                    replaceFileName targetPath (takeFileName sourcePath)+                  else+                    targetPath++    format      = if autoFormat then+                    readProcess (formatterExec language)+                                ["--stdin", finalPath]+                  else+                    pure+++actions :: Opts -> IO ()+actions Opts{language, sourcePath, targetPath, autoFormat, clearContents} =+  when clearContents (removeDirIfExists targetPath)+  >>= const (migrateDirTree sourcePath targetPath)+  >>= writeDirectoryWith writeFileUtf8+  >>= (traverse_ reportFailure) . failures . dirTree+  >>= const format++  where+    removeDirIfExists fp = whenM (removeDirPred fp)+                                 (removeDirectoryRecursive fp)+    removeDirPred fp = andM [doesDirectoryExist fp,+                             (/= fp) <$> getHomeDirectory]+    migrateDirTree fp1 fp2 = convertDirTree language+                             </$> (moveTree fp2+                              <$> (filterDir dirPred+                             </$>  readDirectoryWith readFileUtf8 fp1))+    format = when autoFormat $ callProcess (formatterExec language) [targetPath]++++watchPath :: Opts -> IO ()+watchPath opts@Opts {sourcePath} =+  withManager (\mgr -> watchTree mgr dir pred' (watchAction opts)+                     *> putStrLn ("Watching on: " ++ sourcePath)+                     *> putStrLn ". . ."+                     *> loop)+  where+    dir = takeDirectory sourcePath+    fileName = takeFileName sourcePath+    pred' = watchPred $ wrapMaybe fileName+    loop = forever (threadDelay 1000000)+++watchAction :: Opts -> Action+watchAction opts (Added fp _ _)    = transformAction fp opts+watchAction opts (Modified fp _ _) = transformAction fp opts+watchAction opts (Removed fp _ _)  = removeFile =<< getWatchPath fp opts+watchAction _ _                    = pure ()+++transformAction :: FilePath -> Opts -> IO ()+transformAction fp opts = action (const $ pure ()) =<< newOpts+  where+    newOpts = (\x -> opts{sourcePath = fp, targetPath = x})+              <$> getWatchPath fp opts
+ app/Main.hs view
@@ -0,0 +1,11 @@+module Main where++import CommandLine.Options (optsInfo)+import CommandLine.Process (process)+import Control.Monad       (join)+import Options.Applicative (execParser)+import System.Directory    (getHomeDirectory)+++main :: IO ()+main = join $ process <$> execParser optsInfo <*> getHomeDirectory
+ polyglot.cabal view
@@ -0,0 +1,192 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.35.0.+--+-- see: https://github.com/sol/hpack++name:           polyglot+version:        0.1.1.0+synopsis:       Haskell to Purescript & Scala 3 transpiler+description:    Please see the README on GitHub at <https://github.com/albertprz/polyglot#readme>+category:       Compiler+homepage:       https://github.com/albertprz/polyglot#readme+bug-reports:    https://github.com/albertprz/polyglot/issues+author:         Alberto Perez Lopez+maintainer:     albertoperez1994@gmail.com+copyright:      2022 Alberto Perez Lopez+license:        BSD3+license-file:   LICENSE+build-type:     Simple+extra-source-files:+    README.md++source-repository head+  type: git+  location: https://github.com/albertprz/polyglot++library+  exposed-modules:+      Conversions.ToPurescript.ClassDef+      Conversions.ToPurescript.Common+      Conversions.ToPurescript.DataDef+      Conversions.ToPurescript.FnDef+      Conversions.ToPurescript.ModuleDef+      Conversions.ToPurescript.Pattern+      Conversions.ToPurescript.Type+      Conversions.ToScala.ClassDef+      Conversions.ToScala.Common+      Conversions.ToScala.DataDef+      Conversions.ToScala.FnDef+      Conversions.ToScala.ModuleDef+      Conversions.ToScala.Pattern+      Conversions.ToScala.Type+      Lexers.Haskell.Layout+      Parsers.Haskell.ClassDef+      Parsers.Haskell.Common+      Parsers.Haskell.DataDef+      Parsers.Haskell.FnDef+      Parsers.Haskell.ModuleDef+      Parsers.Haskell.Pattern+      Parsers.Haskell.Type+      SyntaxTrees.Haskell.ClassDef+      SyntaxTrees.Haskell.Common+      SyntaxTrees.Haskell.DataDef+      SyntaxTrees.Haskell.FnDef+      SyntaxTrees.Haskell.ModuleDef+      SyntaxTrees.Haskell.Pattern+      SyntaxTrees.Haskell.Type+      SyntaxTrees.Purescript.ClassDef+      SyntaxTrees.Purescript.Common+      SyntaxTrees.Purescript.DataDef+      SyntaxTrees.Purescript.FnDef+      SyntaxTrees.Purescript.ModuleDef+      SyntaxTrees.Purescript.Pattern+      SyntaxTrees.Purescript.Type+      SyntaxTrees.Scala.Common+      SyntaxTrees.Scala.DataDef+      SyntaxTrees.Scala.FnDef+      SyntaxTrees.Scala.PackageDef+      SyntaxTrees.Scala.Pattern+      SyntaxTrees.Scala.Type+      Utils.Foldable+      Utils.Functor+      Utils.List+      Utils.Maybe+      Utils.String+  other-modules:+      Paths_polyglot+  hs-source-dirs:+      src+  default-extensions:+      LambdaCase+      MultiWayIf+      TupleSections+      PostfixOperators+      BlockArguments+      RankNTypes+      ExplicitForAll+      ScopedTypeVariables+      LiberalTypeSynonyms+      InstanceSigs+      FunctionalDependencies+      DuplicateRecordFields+      NoFieldSelectors+      NamedFieldPuns+      RecordWildCards+      OverloadedRecordDot+      ConstrainedClassMethods+      MultiParamTypeClasses+      FlexibleContexts+      FlexibleInstances+      ApplicativeDo+      ParallelListComp+      MonadComprehensions+      GADTs+      TypeFamilies+      TypeFamilyDependencies+      DataKinds+      PolyKinds+      DeriveFunctor+      DeriveFoldable+      DeriveTraversable+      DeriveGeneric+      GeneralizedNewtypeDeriving+  ghc-options: -Wall -Wcompat -Wincomplete-record-updates -Wincomplete-uni-patterns -Wredundant-constraints+  build-depends:+      base >=4.7 && <5+    , bookhound >=0.1.24 && <0.2+    , bytestring+    , casing >=0.1.4.1 && <0.2+    , containers+    , directory >=1.3.7.0 && <1.4+    , directory-tree >=0.12.1 && <0.13+    , extra >=1.7.10 && <1.8+    , filepath >=1.4.2.2 && <1.5+    , fsnotify >=0.3.0.1 && <0.4+    , optparse-applicative >=0.17.0 && <0.18+    , parallel >=3.2.2.0 && <3.3+    , text >=2 && <2.1+    , utility-ht >=0.0.16 && <0.1+  default-language: Haskell2010++executable polyglot+  main-is: Main.hs+  other-modules:+      CommandLine.FileIO+      CommandLine.Options+      CommandLine.Process+      Paths_polyglot+  hs-source-dirs:+      app+  default-extensions:+      LambdaCase+      MultiWayIf+      TupleSections+      PostfixOperators+      BlockArguments+      RankNTypes+      ExplicitForAll+      ScopedTypeVariables+      LiberalTypeSynonyms+      InstanceSigs+      FunctionalDependencies+      DuplicateRecordFields+      NoFieldSelectors+      NamedFieldPuns+      RecordWildCards+      OverloadedRecordDot+      ConstrainedClassMethods+      MultiParamTypeClasses+      FlexibleContexts+      FlexibleInstances+      ApplicativeDo+      ParallelListComp+      MonadComprehensions+      GADTs+      TypeFamilies+      TypeFamilyDependencies+      DataKinds+      PolyKinds+      DeriveFunctor+      DeriveFoldable+      DeriveTraversable+      DeriveGeneric+      GeneralizedNewtypeDeriving+  ghc-options: -Wall -Wcompat -Wincomplete-record-updates -Wincomplete-uni-patterns -Wredundant-constraints -threaded -rtsopts -with-rtsopts=-N+  build-depends:+      base >=4.7 && <5+    , bookhound >=0.1.24 && <0.2+    , bytestring+    , casing >=0.1.4.1 && <0.2+    , containers+    , directory >=1.3.7.0 && <1.4+    , directory-tree >=0.12.1 && <0.13+    , extra >=1.7.10 && <1.8+    , filepath >=1.4.2.2 && <1.5+    , fsnotify >=0.3.0.1 && <0.4+    , optparse-applicative >=0.17.0 && <0.18+    , parallel >=3.2.2.0 && <3.3+    , polyglot+    , text >=2 && <2.1+    , utility-ht >=0.0.16 && <0.1+  default-language: Haskell2010
+ src/Conversions/ToPurescript/ClassDef.hs view
@@ -0,0 +1,27 @@+module Conversions.ToPurescript.ClassDef where++import qualified SyntaxTrees.Haskell.ClassDef    as H+import qualified SyntaxTrees.Purescript.ClassDef as P++import Conversions.ToPurescript.Common  (class')+import Conversions.ToPurescript.DataDef (derivingStrategy)+import Conversions.ToPurescript.FnDef   (fnDefOrSig)+import Conversions.ToPurescript.Type    (anyKindedType, classConstraint,+                                         typeParam)+++classDef :: H.ClassDef -> P.ClassDef+classDef (H.ClassDef x y z t) =+  P.ClassDef (classConstraint <$> x) (class' y)+             (typeParam <$> z) (fnDefOrSig <$> t)+++instanceDef :: H.InstanceDef -> P.InstanceDef+instanceDef (H.InstanceDef x y z t) =+  P.InstanceDef (classConstraint <$> x) Nothing (class' y)+                (anyKindedType <$> z) (fnDefOrSig <$> t)++derivingDef :: H.DerivingDef -> P.DerivingDef+derivingDef (H.DerivingDef x y z t _) =+  P.DerivingDef (derivingStrategy x) (classConstraint <$> y)+                Nothing (class' z) (anyKindedType <$> t)
+ src/Conversions/ToPurescript/Common.hs view
@@ -0,0 +1,93 @@+module Conversions.ToPurescript.Common where++import qualified SyntaxTrees.Haskell.Common    as H+import qualified SyntaxTrees.Purescript.Common as P++import           Data.Map (Map)+import qualified Data.Map as Map+++var :: H.Var -> P.Var+var (H.Var x) = P.Var $ replaceNaming x++ctor :: H.Ctor -> P.Ctor+ctor (H.Ctor x) = P.Ctor $ replaceNaming x++varOp :: H.VarOp -> P.VarOp+varOp (H.VarOp x) = P.VarOp $ replaceNaming x++ctorOp :: H.CtorOp -> P.CtorOp+ctorOp (H.CtorOp x) = P.CtorOp $ replaceNaming x++varOpFn :: H.Var -> P.Var+varOpFn (H.Var x) = P.Var $ find varOpFnMap $ replaceNaming x++class' :: H.Class -> P.Class+class' (H.Class x) = P.Class x+++module' :: H.Module -> P.Module+module' (H.Module x) = P.Module $ replaceNaming <$> x++qualifier' :: H.Module -> P.Module+qualifier' (H.Module x) = P.Module $ replaceNaming <$> x+++literal :: H.Literal -> P.Literal+literal H.UnitLit       = P.UnitLit+literal (H.BoolLit x)   = P.BoolLit x+literal (H.IntLit x)    = P.IntLit x+literal (H.FloatLit x)  = P.NumberLit x+literal (H.CharLit x)   = P.CharLit x+literal (H.StringLit x) = P.StringLit x++++qVar :: H.QVar -> P.QVar+qVar (H.QVar x y) = P.QVar (qualifier' <$> x) (var y)++qVarOp :: H.QVarOp -> P.QVarOp+qVarOp (H.QVarOp x y) = P.QVarOp (qualifier' <$> x) (varOp y)++qCtor :: H.QCtor -> P.QCtor+qCtor (H.QCtor x y) = P.QCtor (qualifier' <$> x) (ctor y)++qCtorOp :: H.QCtorOp -> P.QCtorOp+qCtorOp (H.QCtorOp x y) = P.QCtorOp (qualifier' <$> x) (ctorOp y)++qClass :: H.QClass -> P.QClass+qClass (H.QClass x y) = P.QClass (qualifier' <$> x) (class' y)+++replaceNaming :: String -> String+replaceNaming x = find charMap <$> find globalMap x++find :: Ord k => Map k k -> k -> k+find x y = Map.findWithDefault y y x++globalMap :: Map String String+globalMap = varOpMap <> ctorOpMap <> varMap <> ctorMap+++charMap :: Map Char Char+charMap = Map.empty++varOpMap :: Map String String+varOpMap = Map.fromList [(".", "<<<"), ("++", "<>"),+                         ("<&>", "<#>"),+                         (",", "/\\"), (",,", "Tuple3"),+                         (",,,", "Tuple4"), (",,,,", "Tuple5")]++ctorOpMap :: Map String String+ctorOpMap = Map.empty++varMap :: Map String String+varMap = Map.fromList [("fmap", "map")]++ctorMap :: Map String String+ctorMap = Map.fromList [("True", "true"), ("False", "false")]++varOpFnMap :: Map String String+varOpFnMap = Map.fromList [("==", "eq"), ("/=", "notEq"),+                         ("<>", "append"), ("<$>", "map"),+                         ("<*>", "apply"), (">>=", "bind") ]
+ src/Conversions/ToPurescript/DataDef.hs view
@@ -0,0 +1,76 @@+module Conversions.ToPurescript.DataDef where++import qualified SyntaxTrees.Haskell.DataDef     as H+import qualified SyntaxTrees.Haskell.Type        as H+import qualified SyntaxTrees.Purescript.ClassDef as P+import qualified SyntaxTrees.Purescript.DataDef  as P+import qualified SyntaxTrees.Purescript.Type     as P++import Conversions.ToPurescript.Common (class', ctor, var)+import Conversions.ToPurescript.Type   (anyKindedType, type', typeCtor,+                                        typeParam)+import SyntaxTrees.Haskell.DataDef     (derivingClasses)+++typeDef :: H.TypeDef -> P.TypeDef+typeDef (H.TypeDef x y z) =+  P.TypeDef (typeCtor x) (typeParam <$> y) (anyKindedType z)+++newtypeDef :: H.NewTypeDef -> (P.NewTypeDef, [P.DerivingDef])+newtypeDef (H.NewTypeDef x y z t u) =+  (newtype', extractDerivingDefs x y u)+  where+    newtype' = P.NewTypeDef (typeCtor x) (typeParam <$> y)+                            (ctor z) (fieldDef t)+++dataDef :: H.DataDef -> (P.DataDef, [P.DerivingDef])+dataDef (H.DataDef x y z u) =+  (data', extractDerivingDefs x y u)+  where+    data' = P.DataDef (typeCtor  x) (typeParam <$> y)+                      (dataCtorDef <$> z)+++dataCtorDef :: H.DataCtorDef -> P.DataCtorDef+dataCtorDef (H.UnNamedFieldsCtor x y) =+  P.UnNamedFieldsCtor (ctor x) (unnamedFieldDef <$> y)+dataCtorDef (H.NamedFieldsCtor x y) =+  P.NamedFieldsCtor (ctor x) (namedFieldDef <$> y)+++fieldDef :: H.FieldDef -> P.FieldDef+fieldDef (H.UnNamedField x) = P.UnNamedField $ unnamedFieldDef x+fieldDef (H.NamedField x)   = P.NamedField $ namedFieldDef x++unnamedFieldDef :: H.UnNamedFieldDef -> P.UnNamedFieldDef+unnamedFieldDef (H.UnNamedFieldDef x) =+  P.UnNamedFieldDef (type' x)++namedFieldDef :: H.NamedFieldDef -> P.NamedFieldDef+namedFieldDef (H.NamedFieldDef x y) =+  P.NamedFieldDef (var x) (type' y)+++extractDerivingDefs :: H.TypeCtor -> [H.TypeParam] -> [H.DerivingClause]+                    -> [P.DerivingDef]+extractDerivingDefs x y z =+  buildDeriving <$> foldMap derivingClasses z+  where+    buildDeriving (strat , cls) =+      P.DerivingDef (derivingStrategy strat) [] Nothing (class' cls) [classType]+    classType = case y of+      [] -> P.TypeValue $ P.TypeVar' $ P.QTypeVar+             (Nothing) (typeCtorToVar $ typeCtor x)+      _ -> P.TypeValue $ P.CtorTypeApply+                (P.QTypeCtor Nothing $ typeCtor x)+                ((P.TypeParam' . typeParam <$> y))++    typeCtorToVar (P.TypeCtor name) = P.TypeVar name+    typeCtorToVar _                 = P.TypeVar mempty+++derivingStrategy :: H.DerivingStrategy -> P.DerivingStrategy+derivingStrategy H.NewTypeDeriving = P.NewTypeDeriving+derivingStrategy _                 = P.StandardDeriving
+ src/Conversions/ToPurescript/FnDef.hs view
@@ -0,0 +1,113 @@+module Conversions.ToPurescript.FnDef where++import qualified SyntaxTrees.Haskell.FnDef     as H+import qualified SyntaxTrees.Haskell.Type      as H+import qualified SyntaxTrees.Purescript.Common as P+import qualified SyntaxTrees.Purescript.FnDef  as P++import Bookhound.Utils.Foldable         (hasNone)+import Conversions.ToPurescript.Common  (literal, qCtor, qCtorOp, qVar, qVarOp,+                                         var, varOp, varOpFn)+import Conversions.ToPurescript.Pattern (pattern')+import Conversions.ToPurescript.Type    (findTypeParams, type')+import Data.Foldable                    (Foldable (toList))+++fnSig :: H.FnSig -> P.FnSig+fnSig (H.FnSig x y) = P.FnSig (varOpFn x) (type' typeScoped)+  where+    typeScoped+      | (H.TypeScope _ _) <- y = y+      | hasNone $ findTypeParams y = y+      | otherwise             = H.TypeScope (toList $ findTypeParams y) y++fnDef :: H.FnDef -> P.FnDef+fnDef (H.FnDef x y z) =+  P.FnDef (varOpFn <$> x) (pattern' <$> y) (maybeGuardedFnBody z)+++infixFnAnnotation :: H.InfixFnAnnotation -> P.InfixFnDef+infixFnAnnotation (H.InfixFnAnnotation x y z) =+  P.InfixFnDef (associativity x) y (P.Var "infixFn") (varOp z)++fnDefOrSig :: H.FnDefOrSig -> P.FnDefOrSig+fnDefOrSig (H.Def x) = P.Def $ fnDef x+fnDefOrSig (H.Sig x) = P.Sig $ fnSig x++fnBody :: H.FnBody -> P.FnBody+fnBody (H.FnApply x y)      = P.FnApply (fnBody x) (fnBody <$> y)+fnBody (H.InfixFnApply x y) = P.InfixFnApply (fnOp <$> x) (fnBody <$> y)++fnBody (H.LeftOpSection x y)    = P.LeftOpSection (fnOp x) (fnBody y)+fnBody (H.RightOpSection x y)   = P.RightOpSection (fnBody x) (fnOp y)+++fnBody (H.LambdaExpr x y)   = P.LambdaExpr (pattern' <$> x) (fnBody y)+fnBody (H.LetExpr x y)      = P.LetExpr (fnDefOrSig <$> x) (fnBody y)+fnBody (H.WhereExpr x y)    = P.WhereExpr (fnBody x) (fnDefOrSig <$> y)++fnBody (H.IfExpr x y z)     = P.IfExpr (fnBody x) (fnBody y) (fnBody z)+fnBody (H.MultiWayIfExpr x) = P.MultiWayIfExpr $ guardedFnBody <$> x+fnBody (H.DoExpr x)         = P.DoExpr $ doStep <$> x+fnBody (H.CaseOfExpr x y)   = P.CaseOfExpr (fnBody x) (caseBinding <$> y)+fnBody (H.LambdaCaseExpr x) = P.LambdaCaseExpr $ caseBinding <$> x+fnBody (H.RecordCreate x y) = P.RecordCreate (fnBody x)+                                ((\(z, t) -> (var z, fnBody t)) <$> y)+fnBody (H.RecordUpdate x y) = P.RecordUpdate (fnBody x)+                                ((\(z, t) -> (var z, fnBody t)) <$> y)++fnBody (H.TypeAnnotation x y) = P.TypeAnnotation (fnBody x) (type' y)+fnBody (H.ListRange x (Just y)) = P.ArrayRange (fnBody x) (fnBody y)+fnBody (H.ListRange x Nothing)  = P.ArrayRange (fnBody x)+  (P.FnVar' $ P.Var' $ P.QVar Nothing $ P.Var "maxBound")+fnBody (H.Tuple x)          = P.Tuple $ fnBody <$> x+fnBody (H.List x)           = P.Array $ fnBody <$> x+fnBody (H.FnOp' x)          = P.FnOp' $ fnOp x+fnBody (H.FnVar' x)         = P.FnVar' $ fnVar x+fnBody (H.Literal' x)       = P.Literal' $ literal x+++fnVar :: H.FnVar -> P.FnVar+fnVar (H.Selector x)    = P.Selector $ var x+fnVar (H.Selection x y) = P.Selection (qVar x) (var <$> y)+fnVar (H.Var' x)        = P.Var' $ qVar x+fnVar (H.Ctor' x)       = P.Ctor' $ qCtor x++fnOp :: H.FnOp -> P.FnOp+fnOp (H.VarOp' x)  = P.VarOp' $ qVarOp x+fnOp (H.CtorOp' x) = P.CtorOp' $ qCtorOp x+++doStep :: H.DoStep -> P.DoStep+doStep (H.DoBinding x y) = P.DoBinding (var <$> x) (fnBody y)+doStep (H.LetBinding x)  = P.LetBinding (fnDefOrSig <$> x)+doStep (H.Body x)        = P.Body $ fnBody x+++caseBinding :: H.CaseBinding -> P.CaseBinding+caseBinding (H.CaseBinding x y) =+  P.CaseBinding (pattern' x) (maybeGuardedFnBody y)+++maybeGuardedFnBody :: H.MaybeGuardedFnBody -> P.MaybeGuardedFnBody+maybeGuardedFnBody (H.Guarded x)  = P.Guarded $ guardedFnBody <$> x+maybeGuardedFnBody (H.Standard x) = P.Standard $ fnBody x+++guardedFnBody :: H.GuardedFnBody -> P.GuardedFnBody+guardedFnBody (H.GuardedFnBody x y) =+  P.GuardedFnBody (guard x) (fnBody y)++guard :: H.Guard -> P.Guard+guard (H.Guard x) = P.Guard $ patternGuard <$> x+guard H.Otherwise = P.Otherwise++patternGuard :: H.PatternGuard -> P.PatternGuard+patternGuard (H.PatternGuard x y) =+  P.PatternGuard (pattern' x) (fnBody y)+patternGuard (H.SimpleGuard x) =+  P.SimpleGuard (fnBody x)++associativity :: H.Associativity -> P.Associativity+associativity H.LAssoc = P.LAssoc+associativity H.RAssoc = P.RAssoc
+ src/Conversions/ToPurescript/ModuleDef.hs view
@@ -0,0 +1,67 @@+module Conversions.ToPurescript.ModuleDef where++import qualified SyntaxTrees.Haskell.ModuleDef    as H+import qualified SyntaxTrees.Haskell.Type         as H+import qualified SyntaxTrees.Purescript.Common    as P+import qualified SyntaxTrees.Purescript.ModuleDef as P++import Conversions.ToPurescript.ClassDef (classDef, derivingDef, instanceDef)+import Conversions.ToPurescript.Common   (module', var, varOp)+import Conversions.ToPurescript.DataDef  (dataDef, newtypeDef, typeDef)+import Conversions.ToPurescript.FnDef    (fnDefOrSig, infixFnAnnotation)+import Conversions.ToPurescript.Type     (typeVar)++++moduleDef :: H.ModuleDef -> P.ModuleDef+moduleDef (H.ModuleDef x y z t) =+  P.ModuleDef (module' x) (moduleExport <$> y)+              (moduleImport <$> z) (foldMap internalDef t)++moduleExport :: H.ModuleExport -> P.ModuleExport+moduleExport (H.ModuleExport x) =+  P.ModuleExport $ moduleExportDef <$> x++moduleExportDef :: H.ModuleExportDef -> P.ModuleExportDef+moduleExportDef (H.ModuleExportDef x)  = P.ModuleExportDef $ importExportDef x+moduleExportDef (H.FullModuleExport x) = P.FullModuleExport $ module' x++moduleImport :: H.ModuleImport -> P.ModuleImport+moduleImport (H.ModuleImport _ x y z t) =+  P.ModuleImport (module' x) z (moduleImportDef <$> t) (module' <$> y)+++moduleImportDef :: H.ModuleImportDef -> P.ModuleImportDef+moduleImportDef (H.ModuleImportDef x)  = P.ModuleImportDef $ importExportDef x+++importExportDef :: H.ImportExportDef -> P.ImportExportDef+importExportDef (H.Member x)       = P.Member $ moduleMember x+importExportDef (H.FullData x)     = P.FullData $ typeVar x+importExportDef (H.FilteredData (H.TypeVar name) y)+  | all isVarMember y = P.FullClass (P.Class name)+importExportDef (H.FilteredData x y) =+  P.FilteredData (typeVar x) (moduleMember <$> y)+++isVarMember :: H.ModuleMember -> Bool+isVarMember (H.VarMember _)   = True+isVarMember (H.VarOpMember _) = True+isVarMember (H.DataMember _)  = False++moduleMember :: H.ModuleMember -> P.ModuleMember+moduleMember (H.VarMember x)   = P.VarMember $ var x+moduleMember (H.VarOpMember x) = P.VarOpMember $ varOp x+moduleMember (H.DataMember x)  = P.DataMember $ typeVar x++internalDef :: H.InternalDef -> [P.InternalDef]+internalDef (H.TypeDef' x)           = [P.TypeDef' $ typeDef x]+internalDef (H.NewTypeDef' x)        =+  (\(y, z) -> P.NewTypeDef' y : (P.DerivingDef' <$> z)) $ newtypeDef x+internalDef (H.DataDef' x)           =+  (\(y, z) -> P.DataDef' y : (P.DerivingDef' <$> z)) $ dataDef x+internalDef (H.FnDefOrSig' x)        = [P.FnDefOrSig' $ fnDefOrSig x]+internalDef (H.ClassDef' x)          = [P.ClassDef' $ classDef x]+internalDef (H.InstanceDef' x)       = [P.InstanceDef' $ instanceDef x]+internalDef (H.DerivingDef' x)       = [P.DerivingDef' $ derivingDef x]+internalDef (H.InfixFnAnnotation' x) = [P.InfixFnDef' $ infixFnAnnotation x]
+ src/Conversions/ToPurescript/Pattern.hs view
@@ -0,0 +1,23 @@+module Conversions.ToPurescript.Pattern where++import qualified SyntaxTrees.Haskell.Pattern    as H+import qualified SyntaxTrees.Purescript.Common  as P+import qualified SyntaxTrees.Purescript.Pattern as P++import Conversions.ToPurescript.Common (literal, qCtor, qCtorOp, var)+++pattern' :: H.Pattern -> P.Pattern+pattern' (H.CtorPattern x y) = P.CtorPattern (qCtor x) (pattern' <$> y)+pattern' (H.InfixCtorPattern x y) = P.InfixCtorPattern (qCtorOp x)+                                                       (pattern' <$> y)+pattern' (H.RecordPattern x y) = P.RecordPattern (qCtor x)+                                ((\(z, t) -> (var z, pattern' <$> t)) <$> y)+pattern' (H.WildcardRecordPattern x y) = pattern' $ H.RecordPattern x y+pattern' (H.AliasedPattern x y) = P.AliasedPattern (var x) (pattern' y)+pattern' (H.ListPattern x) = P.CtorPattern+  (P.QCtor Nothing $ P.Ctor "Array") (pattern' <$> x)+pattern' (H.TuplePattern x) = P.TuplePattern $ pattern' <$> x+pattern' (H.VarPattern x) = P.VarPattern $ var x+pattern' (H.LitPattern x) = P.LitPattern $ literal x+pattern' H.Wildcard = P.Wildcard
+ src/Conversions/ToPurescript/Type.hs view
@@ -0,0 +1,90 @@+module Conversions.ToPurescript.Type where++import qualified SyntaxTrees.Haskell.Type    as H+import qualified SyntaxTrees.Purescript.Type as P++import Conversions.ToPurescript.Common (find, module', qClass)++import Data.Map (Map)+import Data.Set (Set)++import qualified Data.Map as Map+import qualified Data.Set as Set++++typeParam :: H.TypeParam -> P.TypeParam+typeParam (H.TypeParam x) = P.TypeParam  x++typeVar :: H.TypeVar -> P.TypeVar+typeVar (H.TypeVar x) = P.TypeVar $ convertTypeVar x+typeVar H.UnitType    = P.TypeVar "Unit"++typeCtor :: H.TypeCtor -> P.TypeCtor+typeCtor H.Arrow        = P.Arrow+typeCtor H.TupleType    = P.TupleType+typeCtor (H.TypeCtor x) = P.TypeCtor $ convertTypeCtor x+typeCtor H.ListType     = P.TypeCtor "Array"++anyKindedType :: H.AnyKindedType -> P.AnyKindedType+anyKindedType (H.TypeValue x) = P.TypeValue $ type' x+anyKindedType (H.TypeFn x)    = P.TypeFn $ qTypeCtor x+++classConstraint :: H.ClassConstraint -> P.ClassConstraint+classConstraint (H.ClassConstraint x y) =+  P.ClassConstraint (qClass x) (type' <$> y)+++type' :: H.Type -> P.Type+type' (H.CtorTypeApply x y)   = P.CtorTypeApply (qTypeCtor x)+                                                (type' <$> y)+type' (H.ParamTypeApply x y)  = P.ParamTypeApply (typeParam x)+                                                 (type' <$> y)+type' (H.NestedTypeApply x y) = P.NestedTypeApply (type' x) (type' <$> y)+type' (H.TypeVar' x)          = P.TypeVar' $ qTypeVar x+type' (H.TypeParam' x)        = P.TypeParam' $ typeParam x+type' (H.TypeScope x y)       = P.TypeScope (typeParam <$> x) (type' y)+type' (H.ClassScope x y)      = P.ClassScope (classConstraint <$> x)+                                             (type' y)+++findTypeParams :: H.Type -> Set H.TypeParam+findTypeParams (H.CtorTypeApply _ y)   = mconcat $ findTypeParams <$> y+findTypeParams (H.ParamTypeApply x y)  = (Set.singleton x) <>+                                         (mconcat $ findTypeParams <$> y)+findTypeParams (H.NestedTypeApply x y) = mconcat $ findTypeParams <$>+                                         (x : y)+findTypeParams (H.TypeVar' _)          = Set.empty+findTypeParams (H.TypeParam' x)        = Set.singleton x+findTypeParams (H.TypeScope _ _)       = Set.empty+findTypeParams (H.ClassScope _ y)      = findTypeParams y+++extractTypes :: H.Type -> [H.Type]+extractTypes (H.CtorTypeApply (H.QTypeCtor _ H.Arrow) y) = y+extractTypes (H.TypeScope _ y)                           = extractTypes y+extractTypes (H.ClassScope _ y)                          = extractTypes y+extractTypes _                                           = []+++qTypeVar :: H.QTypeVar -> P.QTypeVar+qTypeVar (H.QTypeVar x y) = P.QTypeVar (module' <$> x) (typeVar y)++qTypeCtor :: H.QTypeCtor -> P.QTypeCtor+qTypeCtor (H.QTypeCtor x y) = P.QTypeCtor (module' <$> x) (typeCtor y)+++++convertTypeCtor :: String -> String+convertTypeCtor x = find typeCtorMap x++convertTypeVar :: String -> String+convertTypeVar x = find typeVarMap x++typeCtorMap :: Map String String+typeCtorMap = Map.empty++typeVarMap :: Map String String+typeVarMap = Map.empty
+ src/Conversions/ToScala/ClassDef.hs view
@@ -0,0 +1,40 @@+module Conversions.ToScala.ClassDef where++import qualified SyntaxTrees.Haskell.ClassDef as H+import qualified SyntaxTrees.Haskell.Common   as H+import qualified SyntaxTrees.Scala.Common     as S+import qualified SyntaxTrees.Scala.DataDef    as S+import qualified SyntaxTrees.Scala.FnDef      as S+import qualified SyntaxTrees.Scala.Type       as S++import Conversions.ToScala.FnDef (fnDefOrSigs, fnDefs)+import Conversions.ToScala.Type  (anyKindedType, classConstraint,+                                  findAnyKindedTypeParams, typeParam,+                                  usingArgList)++import Data.Foldable (Foldable (toList))++++classDef :: H.ClassDef -> S.TraitDef+classDef (H.ClassDef x (H.Class y) z t) =+  S.TraitDef [] (S.TypeCtor y)+        (typeParam <$> z) [] [usingArgList $ classConstraint <$> x] []+        (S.Fn . fnDefs <$> fnDefOrSigs t)+++instanceDef :: H.InstanceDef -> S.GivenDef+instanceDef (H.InstanceDef x (H.Class y) z t) =+  S.GivenDef [] Nothing+        (mconcat ((typeParam <$>) . toList . findAnyKindedTypeParams <$> z))+        [usingArgList $ classConstraint <$> x]+        (S.CtorTypeApply (S.QTypeCtor Nothing $ S.TypeCtor y) $ anyKindedType <$> z)+        (Right $ fnDefs <$> fnDefOrSigs t)++derivingDef :: H.DerivingDef -> S.GivenDef+derivingDef (H.DerivingDef _ x (H.Class y) z _) =+  S.GivenDef [] Nothing+        (mconcat ((typeParam <$>) . toList . findAnyKindedTypeParams <$> z))+        [usingArgList $ classConstraint <$> x]+        (S.CtorTypeApply (S.QTypeCtor Nothing $ S.TypeCtor y) $ anyKindedType <$> z)+        (Left $ S.FnVar' $ S.Var' (S.QVar Nothing $ S.Var "derived"))
+ src/Conversions/ToScala/Common.hs view
@@ -0,0 +1,92 @@+module Conversions.ToScala.Common where++import qualified SyntaxTrees.Haskell.Common as H+import qualified SyntaxTrees.Scala.Common   as S++import           Data.Map    (Map)+import qualified Data.Map    as Map+import           Text.Casing (quietSnake)++++var :: H.Var -> S.Var+var (H.Var x) = S.Var $ replaceNaming x++ctor :: H.Ctor -> S.Ctor+ctor (H.Ctor x) = S.Ctor $ replaceNaming x++varOp :: H.VarOp -> S.VarOp+varOp (H.VarOp x) = S.VarOp $ replaceNaming x++ctorOp :: H.CtorOp -> S.CtorOp+ctorOp (H.CtorOp x) = S.CtorOp $ replaceNaming x++class' :: H.Class -> S.TypeClass+class' (H.Class x) = S.TypeClass x+++module' :: H.Module -> S.Package+module' (H.Module x) = S.Package $ (replaceNaming . quietSnake) <$> x++qualifier' :: H.Module -> S.Package+qualifier' (H.Module x) = S.Package $ replaceNaming <$> x+++literal :: H.Literal -> S.Literal+literal H.UnitLit       = S.UnitLit+literal (H.BoolLit x)   = S.BoolLit x+literal (H.IntLit x)    = S.IntLit x+literal (H.FloatLit x)  = S.FloatLit x+literal (H.CharLit x)   = S.CharLit x+literal (H.StringLit x) = S.StringLit x++++qVar :: H.QVar -> S.QVar+qVar (H.QVar x y) = S.QVar (qualifier' <$> x) (var y)++qVarOp :: H.QVarOp -> S.QVarOp+qVarOp (H.QVarOp x y) = S.QVarOp (qualifier' <$> x) (varOp y)++qCtor :: H.QCtor -> S.QCtor+qCtor (H.QCtor x y) = S.QCtor (qualifier' <$> x) (ctor y)++qCtorOp :: H.QCtorOp -> S.QCtorOp+qCtorOp (H.QCtorOp x y) = S.QCtorOp (qualifier' <$> x) (ctorOp y)++qClass :: H.QClass -> S.QTypeClass+qClass (H.QClass x y) = S.QTypeClass (qualifier' <$> x) (class' y)+++replaceNaming :: String -> String+replaceNaming x = find charMap <$> find globalMap x++find :: Ord k => Map k k -> k -> k+find x y = Map.findWithDefault y y x++globalMap :: Map String String+globalMap = varOpMap <> ctorOpMap <> varMap <> ctorMap+++charMap :: Map Char Char+charMap = Map.fromList [('\'', '$'), ('$', '&'), ('.', '|')]++varOpMap :: Map String String+varOpMap = Map.fromList [("$", "|<|"), (".", "^"),+                         ("++", "<+>"), ("<>", "<+>"),+                         (",", "Tuple2"), (",,", "Tuple3"),+                         (",,,", "Tuple4"), (",,,,", "Tuple5")]++ctorOpMap :: Map String String+ctorOpMap = Map.fromList [(":", "::"), ("::", ":")]++varMap :: Map String String+varMap = Map.fromList [("type", "typex"), ("var", "varx"),+                       ("def", "defx"), ("match", "matchx")]++ctorMap :: Map String String+ctorMap = Map.fromList [("Just", "Some"), ("Nothing", "None"),+                       ("True", "true"), ("False", "false")]++autoIds :: [String]+autoIds = pure <$> ['x', 'y', 'z', 't', 'u', 'v', 'w', 'p', 'q', 'r', 's']
+ src/Conversions/ToScala/DataDef.hs view
@@ -0,0 +1,48 @@+module Conversions.ToScala.DataDef where++import qualified SyntaxTrees.Haskell.DataDef as H+import qualified SyntaxTrees.Scala.Common    as S+import qualified SyntaxTrees.Scala.DataDef   as S+import qualified SyntaxTrees.Scala.Type      as S++import Conversions.ToScala.Common  (autoIds, class', ctor, var)+import Conversions.ToScala.Type    (anyKindedType, type', typeCtor, typeParam)+import SyntaxTrees.Haskell.DataDef (derivingClasses)+++typeDef :: H.TypeDef -> S.TypeDef+typeDef (H.TypeDef x y z) =+  S.TypeDef (typeCtor x) (typeParam <$> y) (anyKindedType z)+++newtypeDef :: H.NewTypeDef -> S.OpaqueTypeDef+newtypeDef (H.NewTypeDef x y _  z t) =+  S.OpaqueTypeDef (typeCtor x) (typeParam <$> y)+                  ((.type') $ fieldDef z)+                  (class' <$> foldMap ((snd <$>) . derivingClasses) t)+++dataDef :: H.DataDef -> S.EnumDef+dataDef (H.DataDef x y z t) =+  S.EnumDef [] (typeCtor x) (typeParam <$> y) [] []+               (class' <$> foldMap ((snd <$>) . derivingClasses) t)+               (dataCtorDef <$> z)+++dataCtorDef :: H.DataCtorDef -> S.EnumCaseDef+dataCtorDef (H.NamedFieldsCtor x y) = S.EnumCaseDef (ctor x)+        [S.ArgList $ namedFieldDef <$> y] [] [] []+dataCtorDef (H.UnNamedFieldsCtor x y) = S.EnumCaseDef (ctor x)+        [S.ArgList $ uncurry unNamedFieldDef <$> zip autoIds y] [] [] []+++fieldDef :: H.FieldDef -> S.ArgField+fieldDef (H.NamedField x)   = namedFieldDef x+fieldDef (H.UnNamedField x) = unNamedFieldDef "value" x+++namedFieldDef :: H.NamedFieldDef -> S.ArgField+namedFieldDef (H.NamedFieldDef x y) = S.ArgField [] (var x) (type' y)++unNamedFieldDef :: String -> H.UnNamedFieldDef -> S.ArgField+unNamedFieldDef x (H.UnNamedFieldDef y) = S.ArgField [] (S.Var x) (type' y)
+ src/Conversions/ToScala/FnDef.hs view
@@ -0,0 +1,271 @@+module Conversions.ToScala.FnDef where++import qualified SyntaxTrees.Haskell.Common as H+import qualified SyntaxTrees.Haskell.FnDef  as H+import qualified SyntaxTrees.Haskell.Type   as H+import qualified SyntaxTrees.Scala.Common   as S+import qualified SyntaxTrees.Scala.FnDef    as S+import qualified SyntaxTrees.Scala.Pattern  as S++import Conversions.ToScala.Common  (autoIds, literal, qCtor, qCtorOp, qVar,+                                    qVarOp, var)+import Conversions.ToScala.Pattern (allVars, extractVars, pattern')+import Conversions.ToScala.Type    (argLists, classScopeSplit, findTypeParams,+                                    typeParam, typeSplit, usingArgList)++import Data.Foldable           (Foldable (fold, toList))+import Data.List               (nubBy)+import Data.Maybe              (fromMaybe, isJust, listToMaybe, mapMaybe)+import Data.Tuple.Extra        (uncurry3, (***))+import SyntaxTrees.Scala.FnDef (WhenExpr (..))+import Utils.List              (groupTuplesByKey, mergeUnion)+++emptyFnSig :: S.FnSig+emptyFnSig = S.FnSig [] [] [] Nothing++namedFnSig :: H.Type -> [H.Var] -> S.FnSig+namedFnSig tpe args = S.FnSig (typeParam <$> (toList $ findTypeParams tpe))+                      (argLists (var <$> args) argTypes)+                      [usingArgList constraints]+                      (Just retType)+  where+    (constraints, rest) = classScopeSplit tpe+    (argTypes, retType) = typeSplit (length args) rest+++unNamedFnSig :: H.Type -> Int -> S.FnSig+unNamedFnSig tpe n = S.FnSig (typeParam <$> (toList $ findTypeParams tpe))+                     (argLists (S.Var <$> autoIds) argTypes)+                     [usingArgList constraints]+                     (Just retType)+  where+    (constraints, rest) = classScopeSplit tpe+    (argTypes, retType) = typeSplit n rest+++fnDefOrSigs :: [H.FnDefOrSig] -> [(Maybe H.FnSig, Maybe [H.FnDef])]+fnDefOrSigs defsOrSigs = nubBy dedupFn $ mergeUnion sigs groupedDefs++  where+    dedupFn x y = any isJust [fst x, fst y] &&+                  ((.name) <$> fst x) == ((.name) <$> fst y)+    defs = mapMaybe (\case (H.Def x) -> Just (head x.names, x)+                           (H.Sig _) -> Nothing)+           defsOrSigs+    sigs = mapMaybe (\case (H.Def _) -> Nothing+                           (H.Sig x) -> Just (x.name, x))+           defsOrSigs+    groupedDefs = groupTuplesByKey defs++++fnDefs :: (Maybe H.FnSig, Maybe [H.FnDef]) -> S.InternalFnDef+fnDefs (x, Just [y])+  | length  y.names > 1 = valDef y+  | allVars y.args      = simpleFnDef x y+fnDefs (x, y)           = fnDef x y+++fnDef :: Maybe H.FnSig -> Maybe [H.FnDef] -> S.InternalFnDef+fnDef sig defs = S.FnMethod $ S.MethodDef [] name fnSig+                              (matchFn . fnDefToFnBody <$> defs)+  where+    n = maybe 0 (length . (.args)) $ (listToMaybe . fold) defs+    fnSig =  (`unNamedFnSig` n') . (.type') <$> sig+    name = var $ maybe (head . (.names) . head $ fromMaybe [] defs) (.name) sig+    (n', matchFn) = if n == 1 then (0, topLevelMatch) else (n, id)++simpleFnDef :: Maybe H.FnSig -> H.FnDef -> S.InternalFnDef+simpleFnDef sig def = S.FnMethod $ S.MethodDef [] name fnSig+                                               (Just $ simpleFnDefToFnBody def)+  where+    name = var $ head def.names+    args = extractVars $ (.args) def+    fnSig = (`namedFnSig` args) . (.type') <$> sig++valDef :: H.FnDef -> S.InternalFnDef+valDef def = S.FnVal $ S.ValDef [S.Lazy] names Nothing+                                (Just $ simpleFnDefToFnBody def)+  where+    names = var <$> def.names+++simpleFnDefToFnBody :: H.FnDef -> S.FnBody+simpleFnDefToFnBody def = maybeGuardedBody . (.body) $ def++fnDefToFnBody :: [H.FnDef] -> S.FnBody+fnDefToFnBody defs = match+  where+    match = simplifyMatch $+      S.MatchExpr (tuple $ take n autoIds) cases+    casePatterns = (S.TuplePattern  . (pattern' <$>) . (.args)) <$> defs+    caseBodies =  (maybeGuardedBody . (.body)) <$> defs+    cases = uncurry3 S.CaseBinding <$> zip3 casePatterns (repeat Nothing)+                                              caseBodies+    tuple x = S.Tuple $ (S.FnVar' . S.Var' . S.QVar Nothing . S.Var) <$> x+    n = (length . (.args)) (head defs)++++fnBody :: H.FnBody -> S.FnBody+fnBody (H.FnApply x y)      = S.FnApply (fnBody x) (fnBody <$> y)+fnBody (H.InfixFnApply x y) = S.InfixFnApply (fnOp <$> x) (fnBody <$> y)++fnBody (H.LeftOpSection x y) = S.LambdaExpr [] (S.InfixFnApply [fnOp x]+        [S.FnVar' $ S.Var' $ S.QVar Nothing $ S.Var "_", fnBody y])++fnBody (H.RightOpSection x y) = S.LambdaExpr [] (S.InfixFnApply [fnOp y]+        [fnBody x, S.FnVar' $ S.Var' $ S.QVar Nothing $ S.Var "_"])++fnBody (H.LambdaExpr x y)   = S.LambdaExpr (pattern' <$> x)+                                          (fnBody y)+fnBody (H.IfExpr x y z)     = S.IfExpr (fnBody x) (fnBody y) (fnBody z)+fnBody (H.DoExpr x)         = S.ForExpr (doStep <$> init x) (extractDoStep $ last x)+fnBody (H.MultiWayIfExpr x) = maybeGuardedBody $ H.Guarded x+fnBody (H.CaseOfExpr x y)   = simplifyMatch $+                              S.MatchExpr (fnBody x) (caseBinding <$> y)+fnBody (H.LambdaCaseExpr x) = S.LambdaExpr [] (fnBody $ H.CaseOfExpr+                              (H.FnVar' $ H.Var' $ H.QVar Nothing $ H.Var "_") x)++fnBody (H.TypeAnnotation x _) = fnBody x+fnBody (H.ListRange x (Just y)) = S.InfixFnApply+    [S.VarOp' $ S.QVarOp Nothing $ S.VarOp "to"] [fnBody x, fnBody y]+fnBody (H.ListRange x Nothing)  = S.InfixFnApply+    [S.VarOp' $ S.QVarOp Nothing $ S.VarOp "to"]+    [fnBody x, S.FnVar' $ S.Var' $ S.QVar Nothing $ S.Var "maxBound"]+fnBody (H.Tuple x)          = S.Tuple $ fnBody <$> x+fnBody (H.FnOp' x)          = S.FnOp' $ fnOp x+fnBody (H.FnVar' x)         = fnVar x+fnBody (H.Literal' x)       = S.Literal' $ literal x++fnBody (H.List [])        = S.FnApply+        (S.FnVar' $ S.Ctor' $ S.QCtor (Just $ S.Package ["List"])+                                      (S.Ctor "empty")) []+fnBody (H.List x)        = S.FnApply+        (S.FnVar' $ S.Ctor' $ S.QCtor Nothing $ S.Ctor "List")+                                     (fnBody <$> x)+fnBody (H.LetExpr x y)   = S.LetExpr (fnDefs <$> fnDefOrSigs x)+                                     (fnBody y)+fnBody (H.WhereExpr x y) = S.LetExpr (fnDefs <$> fnDefOrSigs y)+                                     (fnBody x)+fnBody (H.RecordCreate x y) = S.NamedFnApply (fnBody x)+                                             ((var *** fnBody) <$> y)+fnBody (H.RecordUpdate x y) =+  S.NamedFnApply (S.BodySelection (fnBody x) [S.Var "copy"])+                 ((var *** fnBody) <$> y)++++doStep :: H.DoStep -> S.ForStep+doStep (H.DoBinding x y) = S.ForBinding (var <$> x) (fnBody y)+doStep (H.LetBinding x)  = S.LetBinding (fnDefs <$> fnDefOrSigs x)+doStep (H.Body x)        = S.ForBinding [S.Var "_"] (fnBody x)++++caseBinding :: H.CaseBinding -> S.CaseBinding+caseBinding (H.CaseBinding x y) = S.CaseBinding (pattern' x) Nothing+                                                (maybeGuardedBody y)+++simplifyMatch :: S.FnBody -> S.FnBody+simplifyMatch (S.MatchExpr x y) = S.MatchExpr x (foldMap simplifyCases y)+simplifyMatch x                 = x++topLevelMatch :: S.FnBody -> S.FnBody+topLevelMatch (S.MatchExpr _ y) = S.TopLevelMatchExpr y+topLevelMatch x                 = x+++simplifyCases :: S.CaseBinding -> [S.CaseBinding]+simplifyCases (S.CaseBinding x' Nothing (S.MatchExpr _ y))+  | all (isJust . simpleCase) y = uncurry (S.CaseBinding x') <$> z+    where+      z = mapMaybe simpleCase y+simplifyCases x = [x]+++simpleCase :: S.CaseBinding -> Maybe (Maybe S.FnBody, S.FnBody)+simpleCase (S.CaseBinding S.Wildcard x y) = Just (x, y)+simpleCase _                              = Nothing+++maybeGuardedBody :: H.MaybeGuardedFnBody -> S.FnBody+maybeGuardedBody (H.Guarded x)+  | H.Otherwise <-  last guards+  , all onlySimpleGuards $ init guards+  = S.CondExpr whenBranches elseBranch+  where+    guards = (.guard) <$> x+    bodies = fnBody . (.body)  <$> x+    conds = aggregateConds . (fnBody <$>) . extractSimpleGuards <$> (init guards)+    whenBranches = uncurry WhenExpr <$> zip conds (init bodies)+    elseBranch = last bodies++maybeGuardedBody (H.Guarded x)  = simplifyMatch $+  S.MatchExpr (S.Literal' $ S.BoolLit True) (guardedBody <$> x)+maybeGuardedBody (H.Standard x) = fnBody x+++guardedBody :: H.GuardedFnBody -> S.CaseBinding+guardedBody (H.GuardedFnBody x@(H.Guard y) body)+      | onlySimpleGuards x =+        S.CaseBinding S.Wildcard (Just $ aggregateConds $+                                         fnBody <$> extractSimpleGuards x)+                                 (fnBody body)++      | otherwise =+        S.CaseBinding S.Wildcard Nothing $ foldr patternGuard (fnBody body) y++guardedBody (H.GuardedFnBody H.Otherwise body) =+  S.CaseBinding S.Wildcard Nothing $ fnBody body+++patternGuard :: H.PatternGuard -> S.FnBody -> S.FnBody+patternGuard (H.PatternGuard x y) body = simplifyMatch $+  S.MatchExpr+        (fnBody y)+        [S.CaseBinding (pattern' x) Nothing body]++patternGuard (H.SimpleGuard x) body = simplifyMatch $+  S.MatchExpr+        (S.Literal' $ S.BoolLit True)+        [S.CaseBinding S.Wildcard (Just (fnBody x)) body]+++fnVar :: H.FnVar -> S.FnBody+fnVar (H.Selector x)    = S.LambdaExpr [] $ S.FnVar' $+                                S.Selection (S.QVar Nothing $ S.Var "_") [var x]+fnVar (H.Selection x y) = S.FnVar' $ S.Selection (qVar x) (var <$> y)+fnVar (H.Var' x)        = S.FnVar' $ S.Var' $ qVar x+fnVar (H.Ctor' x)       = S.FnVar' $ S.Ctor' $ qCtor x+++fnOp :: H.FnOp -> S.FnOp+fnOp (H.VarOp' x)  = S.VarOp' $ qVarOp x+fnOp (H.CtorOp' x) = S.CtorOp' $ qCtorOp x+++extractDoStep :: H.DoStep -> S.FnBody+extractDoStep (H.DoBinding _ y) = fnBody y+extractDoStep (H.Body x)        = fnBody x+extractDoStep (H.LetBinding  _) = S.Tuple []+++extractSimpleGuards :: H.Guard -> [H.FnBody]+extractSimpleGuards (H.Guard x) =+  foldMap (\case (H.SimpleGuard y) -> [y]; _ -> []) x+extractSimpleGuards _ = []+++onlySimpleGuards :: H.Guard -> Bool+onlySimpleGuards (H.Guard x) =+  all (\case (H.SimpleGuard _) -> True; _ -> False ) x+onlySimpleGuards H.Otherwise = False+++aggregateConds :: [S.FnBody] -> S.FnBody+aggregateConds [x] = x+aggregateConds x = S.InfixFnApply+                     [S.VarOp' $ S.QVarOp Nothing $ S.VarOp "&&"] x
+ src/Conversions/ToScala/ModuleDef.hs view
@@ -0,0 +1,80 @@+module Conversions.ToScala.ModuleDef where++import qualified SyntaxTrees.Haskell.ModuleDef as H+import qualified SyntaxTrees.Scala.DataDef     as S+import qualified SyntaxTrees.Scala.FnDef       as S+import qualified SyntaxTrees.Scala.PackageDef  as S++import Conversions.ToScala.ClassDef (classDef, derivingDef, instanceDef)+import Conversions.ToScala.Common   (module', qualifier', var, varOp)+import Conversions.ToScala.DataDef  (dataDef, newtypeDef, typeDef)+import Conversions.ToScala.FnDef    (fnDefOrSigs, fnDefs)+import Conversions.ToScala.Type     (typeVar)++import Data.Maybe     (mapMaybe, maybeToList)+import Utils.Foldable (wrapMaybe)+import Utils.Maybe    (cond)++++moduleDef :: H.ModuleDef -> S.PackageDef+moduleDef (H.ModuleDef x _ z t) =+  S.PackageDef (module' x) (moduleImport =<< z) (internalDefs t)+++moduleImport :: H.ModuleImport -> [S.PackageImport]+moduleImport (H.ModuleImport True x Nothing _ y) =+  moduleImport $ H.ModuleImport True x (Just x) False y+moduleImport (H.ModuleImport x y z _ []) =+  [S.PackageImport (module' y) (qualifier' <$> z)+   (cond (not x) S.FullImport)]+moduleImport (H.ModuleImport x y z _ t) =+  S.PackageImport (module' y) (qualifier' <$> z) . (cond (not x))+  <$> moduleImportDefs t++moduleImportDefs :: [H.ModuleImportDef] -> [S.PackageImportDef]+moduleImportDefs importDefs = maybeToList combined ++ singles+  where+    combined = S.MembersImport <$> wrapMaybe (mapMaybe singleImportDef importDefs)+    singles = mapMaybe complexImportDef importDefs+++complexImportDef :: H.ModuleImportDef -> Maybe S.PackageImportDef+complexImportDef (H.ModuleImportDef (H.FullData x)) =+  Just $ S.FullObjectImport $ typeVar x+complexImportDef (H.ModuleImportDef (H.FilteredData x y)) =+  S.FilteredObjectImport (typeVar x) <$> wrapMaybe (moduleMember <$> y)+complexImportDef _ = Nothing+++singleImportDef :: H.ModuleImportDef -> Maybe S.PackageMember+singleImportDef (H.ModuleImportDef (H.Member x)) = Just $ moduleMember x+singleImportDef _                                = Nothing+++internalDefs :: [H.InternalDef] -> [S.InternalDef]+internalDefs defs =+  (mapMaybe internalDef others) +++  (S.Fn . fnDefs <$> fnDefOrSigs fns)++  where+    fns    = mapMaybe (\case (H.FnDefOrSig' x) -> Just x+                             _                 -> Nothing) defs++    others = mapMaybe (\case (H.FnDefOrSig' _) -> Nothing+                             x                 -> Just x) defs++internalDef :: H.InternalDef -> Maybe S.InternalDef+internalDef (H.TypeDef' x)           = Just $ S.TypeAlias $ typeDef x+internalDef (H.NewTypeDef' x)        = Just $ S.OpaqueType $ newtypeDef x+internalDef (H.DataDef' x)           = Just $ S.Enum $ dataDef x+internalDef (H.ClassDef' x)          = Just $ S.Trait $ classDef x+internalDef (H.InstanceDef' x)       = Just $ S.Fn $ S.FnGiven $ instanceDef x+internalDef (H.DerivingDef' x)       = Just $ S.Fn $ S.FnGiven $ derivingDef x+internalDef (H.FnDefOrSig' _)        = Nothing+internalDef (H.InfixFnAnnotation' _) = Nothing++moduleMember :: H.ModuleMember -> S.PackageMember+moduleMember (H.VarMember x)   = S.VarMember $ var x+moduleMember (H.VarOpMember x) = S.VarOpMember $ varOp x+moduleMember (H.DataMember x)  = S.DataMember $ typeVar x
+ src/Conversions/ToScala/Pattern.hs view
@@ -0,0 +1,45 @@+module Conversions.ToScala.Pattern where++import qualified SyntaxTrees.Haskell.Common  as H+import qualified SyntaxTrees.Haskell.Pattern as H+import qualified SyntaxTrees.Scala.Common    as S+import qualified SyntaxTrees.Scala.Pattern   as S++import Conversions.ToScala.Common (literal, qCtor, qCtorOp, var)+import Data.Maybe                 (mapMaybe)+++pattern' :: H.Pattern -> S.Pattern+pattern' (H.CtorPattern x y) = S.CtorPattern (qCtor x) (pattern' <$> y)+pattern' (H.InfixCtorPattern x y) = S.InfixCtorPattern (qCtorOp x) (pattern' <$> y)+pattern' (H.RecordPattern x y) = S.CtorPattern (qCtor x)+                                               (S.VarPattern . var . fst <$> y)+pattern' (H.WildcardRecordPattern x y) = S.CtorPattern (qCtor x)+                                               (S.VarPattern . var . fst <$> y)+pattern' (H.AliasedPattern x y) = S.AliasedPattern (var x) (pattern' y)+pattern' (H.ListPattern x) = S.CtorPattern  (S.QCtor Nothing $ S.Ctor "List") (pattern' <$> x)+pattern' (H.TuplePattern x) = S.TuplePattern $ pattern' <$> x+pattern' (H.VarPattern x) = S.VarPattern $ var x+pattern' (H.LitPattern x) = S.LitPattern $ literal x+pattern' H.Wildcard = S.Wildcard+++extractVar :: H.Pattern -> Maybe H.Var+extractVar (H.VarPattern x) = Just x+extractVar _                = Nothing++extractVars :: [H.Pattern] -> [H.Var]+extractVars x = mapMaybe extractVar x++allVars :: [H.Pattern] -> Bool+allVars x = length (mapMaybe extractVar x) == length x++extractVar' :: S.Pattern -> Maybe S.Var+extractVar' (S.VarPattern x) = Just x+extractVar' _                = Nothing++extractVars' :: [S.Pattern] -> [S.Var]+extractVars' x = mapMaybe extractVar' x++allVars' :: [S.Pattern] -> Bool+allVars' x = length (mapMaybe extractVar' x) == length x
+ src/Conversions/ToScala/Type.hs view
@@ -0,0 +1,124 @@+module Conversions.ToScala.Type where++import qualified SyntaxTrees.Haskell.Type as H+import qualified SyntaxTrees.Scala.Common as S+import qualified SyntaxTrees.Scala.Type   as S++import Conversions.ToScala.Common (find, qClass, qualifier')++import Data.Char (toUpper)+import Data.Map  (Map)+import Data.Set  (Set)++import qualified Data.Map as Map+import qualified Data.Set as Set++++typeParam :: H.TypeParam -> S.TypeParam+typeParam (H.TypeParam x) = S.TypeParam $ toUpper <$> x++typeVar :: H.TypeVar -> S.TypeVar+typeVar (H.TypeVar x) = S.TypeVar $ convertTypeVar x+typeVar H.UnitType    = S.TypeVar "Unit"++typeCtor :: H.TypeCtor -> S.TypeCtor+typeCtor H.Arrow        = S.Arrow+typeCtor H.TupleType    = S.TupleType+typeCtor (H.TypeCtor x) = S.TypeCtor $ convertTypeCtor x+typeCtor H.ListType     = S.TypeCtor "List"++anyKindedType :: H.AnyKindedType -> S.Type+anyKindedType (H.TypeValue x) = type' x+anyKindedType (H.TypeFn (H.QTypeCtor _ H.ListType)) =+  S.CtorTypeApply (S.QTypeCtor Nothing $ S.TypeCtor "List") [S.ExistentialType]+anyKindedType (H.TypeFn (H.QTypeCtor _ H.Arrow)) =+  S.CtorTypeApply (S.QTypeCtor Nothing $ S.TypeCtor "Function2")+                                             [S.ExistentialType, S.ExistentialType]+anyKindedType (H.TypeFn (H.QTypeCtor _ H.TupleType)) =+  S.CtorTypeApply (S.QTypeCtor Nothing $ S.TypeCtor "Tuple2")+                                             [S.ExistentialType, S.ExistentialType]+anyKindedType (H.TypeFn x@(H.QTypeCtor _ _)) = S.CtorTypeApply (qTypeCtor x)+                                             [S.ExistentialType]+++classConstraint :: H.ClassConstraint -> S.ClassConstraint+classConstraint (H.ClassConstraint x y) = S.ClassConstraint (qClass x) (type' <$> y)+++type' :: H.Type -> S.Type+type' (H.CtorTypeApply x y)   = S.CtorTypeApply (qTypeCtor x) (type' <$> y)+type' (H.ParamTypeApply x y)  = S.ParamTypeApply (typeParam x) (type' <$> y)+type' (H.NestedTypeApply x y) = S.NestedTypeApply (type' x) (type' <$> y)+type' (H.TypeVar' x)          = S.TypeVar' $ qTypeVar x+type' (H.TypeParam' x)        = S.TypeParam' $ typeParam x+type' (H.TypeScope x y)       = S.TypeScope (typeParam <$> x) (type' y)+type' (H.ClassScope x y)      = S.ClassScope (classConstraint <$> x) (type' y)+++typeSplit :: Int -> H.Type -> ([S.Type], S.Type)+typeSplit 0 tpe = ([], type' tpe)+typeSplit n tpe = (args, S.CtorTypeApply (S.QTypeCtor Nothing S.Arrow) ret)+  where+    (args, ret) = splitAt (min n (length types - 1)) (type' <$> types)+    types = extractTypes tpe+++classScopeSplit :: H.Type -> ([S.ClassConstraint], H.Type)+classScopeSplit (H.ClassScope x y) = (classConstraint <$> x, y)+classScopeSplit x                  = ([], x)+++findAnyKindedTypeParams :: H.AnyKindedType -> Set H.TypeParam+findAnyKindedTypeParams (H.TypeValue x) = findTypeParams x+findAnyKindedTypeParams _               = Set.empty+++findTypeParams :: H.Type -> Set H.TypeParam+findTypeParams (H.CtorTypeApply _ y)   = mconcat $ findTypeParams <$> y+findTypeParams (H.ParamTypeApply x y)  = (Set.singleton x) <>+                                         (mconcat $ findTypeParams <$> y)+findTypeParams (H.NestedTypeApply x y) = mconcat $ findTypeParams <$> (x : y)+findTypeParams (H.TypeVar' _)          = Set.empty+findTypeParams (H.TypeParam' x)        = Set.singleton x+findTypeParams (H.TypeScope _ _)       = Set.empty+findTypeParams (H.ClassScope _ y)      = findTypeParams y+++extractTypes :: H.Type -> [H.Type]+extractTypes (H.CtorTypeApply (H.QTypeCtor _ H.Arrow) y) = y+extractTypes (H.TypeScope _ y)                           = extractTypes y+extractTypes (H.ClassScope _ y)                          = extractTypes y+extractTypes _                                           = []+++argLists :: [S.Var] -> [S.Type] -> [S.ArgList]+argLists args argTypes =+  S.ArgList . pure . uncurry (S.ArgField []) <$> zip args argTypes+++usingArgList :: [S.ClassConstraint] -> S.UsingArgList+usingArgList constraints =+  S.UsingArgList $ (S.UsingArgField [] Nothing) <$> constraints+++qTypeVar :: H.QTypeVar -> S.QTypeVar+qTypeVar (H.QTypeVar x y) = S.QTypeVar (qualifier' <$> x) (typeVar y)++qTypeCtor :: H.QTypeCtor -> S.QTypeCtor+qTypeCtor (H.QTypeCtor x y) = S.QTypeCtor (qualifier' <$> x) (typeCtor y)+++++convertTypeCtor :: String -> String+convertTypeCtor x =  find typeCtorMap x++convertTypeVar :: String -> String+convertTypeVar x =  find typeVarMap x++typeCtorMap :: Map String String+typeCtorMap = Map.fromList [("Maybe", "Option")]++typeVarMap :: Map String String+typeVarMap = Map.fromList [("Type", "Typex")]
+ src/Lexers/Haskell/Layout.hs view
@@ -0,0 +1,119 @@+module Lexers.Haskell.Layout where+++import Parsers.Haskell.Common (anyComment)++import Utils.Foldable (hasNone, hasSome)+import Utils.List     (safeHead, safeTail)+import Utils.String   (joinWords, wrapCurly', wrapDoubleQuotes', wrapParens',+                       wrapQuotes')+++import Bookhound.Parser            (ParseError, Parser, check, runParser,+                                    withError)+import Bookhound.ParserCombinators (IsMatch (is, isNot, noneOf, oneOf), (->>-),+                                    (<|>), (|*), (|+), (|?))+import Bookhound.Parsers.Char      (char, space)+import Bookhound.Parsers.String    (spacing, withinDoubleQuotes, withinParens,+                                    withinQuotes, word)+++import Control.Monad  (foldM)+import Data.Foldable  (Foldable (fold))+import Data.List      (isPrefixOf)+import Data.Monoid.HT (when)+import Data.Text      (Text, pack)+++adaptLayout :: Text -> Either [ParseError] Text+adaptLayout str = pack . (++ " }") . unlines . fst4 <$> layoutLines+  where+    layoutLines = foldM layout args . (++ pure "") . filter hasSome =<< input+    input = lines . fold <$> runParser parensLayout str+    args = ([], [], False, False)+    fst4 (x, _, _, _) = x+++layout :: ([String], [Int], Bool, Bool) -> String -> Either [ParseError] ([String], [Int], Bool, Bool)+layout (x, y, z, t) str = runParser layoutParser $ pack str+  where+    layoutParser = withError "Layout lexer" $+      do spaces' <- (space |*)+         beginning <- otherText+         layoutText <- (layoutBegin |?)+         spaces'' <- (space |*)+         rest <- otherText+         let hasIn = maybe False ("in" ==) (safeHead $ words beginning)+             hasCurly = isPrefixOf "{" rest+             indents = when z [length spaces'] +++                if not hasIn then y+                else (length spaces' + 1) : (fold $ safeTail y)+             layoutNextLine = hasSome layoutText && hasNone rest+             contextIndent = length $ spaces' ++ beginning ++ fold layoutText ++ spaces''+             (newIndents, beginSep, stop) = calcIndent indents (length spaces')+                                            (t || hasCurly) beginning+             endSep = when (hasSome layoutText && not hasCurly) " {"+             indents' = when (hasSome layoutText && hasSome rest)+                        [contextIndent] ++ newIndents+             text = x ++ [spaces' ++ beginSep ++ beginning ++ fold+                          layoutText ++ endSep ++  spaces'' ++ rest]+         pure $ (text, indents', layoutNextLine, stop || hasCurly)+++parensLayout :: Parser [String]+parensLayout = (((spacing |?) ->>- elem'+               <|> parensParser+               <|> (wrapParens' . fold <$> withinParens parensLayout) ->>-+                   (spacing |?)) |*)+  where+    elem' = lexeme' id+    parensParser = wrapParens' <$> withinParens+                ((spacing |?) ->>- layoutBegin ->>- spacing ->>-+                 (wrapCurly' . fold <$> parensLayout))++++calcIndent :: [Int] -> Int -> Bool -> String -> ([Int], String, Bool)+calcIndent indentLvls curr stop beginning =+  (newIndentLvls, joinWords [closeContexts, sep], shouldStop)+  where+    extraElems = if not stop then extra else fold $ safeTail extra+    closeContexts = fold ("} " <$ extraElems)+    shouldStop = stop && hasNone extra+    sep = when (any (== curr) (safeHead newIndentLvls) &&+                notElem beginning nestTokens) "; "+    (extra, newIndentLvls) = span (curr <) indentLvls+++nestTokens :: [String]+nestTokens = ["then", "else"]++layoutTokens :: [String]+layoutTokens = [("(" ++), id] <*> ["where", "let", "do", "of", "\\case"]++layoutBegin :: Parser String+layoutBegin = oneOf layoutTokens++lexeme :: Parser String+lexeme = wrapDoubleQuotes' <$> withinDoubleQuotes (isNot '"'  |+)+  <|> wrapQuotes' . pure <$> withinQuotes (char <|> (is '\\' |?) *> char)+  <|> anyComment+  <|> word++++otherText :: Parser String+otherText = fold <$> elems+  where+    elems = (((check "" (`notElem` layoutTokens) lexeme) ->>- (space |*)) |*)+++lexeme' :: (Parser String -> Parser String) -> Parser String+lexeme' f = (spacing |?) ->>- f lexeme ->>- (spacing |?)++otherText' :: Parser String+otherText' = lexeme' (check "" (`notElem` layoutTokens))+++word' :: Parser String+word' = ((noneOf [' ', '\n', '\t', '(', ')']) |+)
+ src/Parsers/Haskell/ClassDef.hs view
@@ -0,0 +1,54 @@+module Parsers.Haskell.ClassDef where++import SyntaxTrees.Haskell.ClassDef (ClassDef (..), DerivingDef (..),+                                     InstanceDef (..))+import SyntaxTrees.Haskell.Type     (ClassConstraint)++import Parsers.Haskell.Common (class')+import Parsers.Haskell.FnDef  (fnDefOrSig, withinContext)+import Parsers.Haskell.Type   (anyKindedType, classConstraints, type',+                               typeParam)++import Bookhound.Parser            (Parser, withError)+import Bookhound.ParserCombinators (IsMatch (is), (<|>), (|*), (|+), (|?))++import Data.Foldable               (Foldable (fold))+import SyntaxTrees.Haskell.DataDef (DerivingStrategy (..))+++classDef :: Parser ClassDef+classDef = withError "Class declaration" $+  ClassDef <$> (is "class" *> classConstraints')+           <*> class'+           <*> (typeParam |*)+           <* is "where"+           <*> withinContext fnDefOrSig+++instanceDef :: Parser InstanceDef+instanceDef = withError "Instance declaration" $+  InstanceDef <$> (is "instance" *> classConstraints')+              <*> class'+              <*> (anyKindedType |+)+              <* is "where"+              <*> withinContext fnDefOrSig++derivingDef :: Parser DerivingDef+derivingDef = withError "Standalone deriving declaration" $+  DerivingDef <$> (is "deriving" *>+                   derivingStrategy <* is "instance")+              <*> classConstraints'+              <*> class'+              <*> (anyKindedType |+)+              <*> ((is "via" *> class') |?)++derivingStrategy :: Parser DerivingStrategy+derivingStrategy = (StandardDeriving <$ is "stock")+                   <|> (NewTypeDeriving <$ is "newtype")+                   <|> (AnyClassDeriving <$ is "anyclass")+                   <|> pure StandardDeriving+++classConstraints' :: Parser [ClassConstraint]+classConstraints' = fold <$>+                    ((classConstraints type' <* is "=>") |?)
+ src/Parsers/Haskell/Common.hs view
@@ -0,0 +1,172 @@+module Parsers.Haskell.Common where++import Data.Foldable (Foldable (fold))+++import Bookhound.Parser            (Parser, check, withTransform)+import Bookhound.ParserCombinators (IsMatch (inverse, is, isNot, noneOf, oneOf),+                                    maybeWithin, someSepBy, within, withinBoth,+                                    (->>-), (<|>), (|*), (|+), (|?))+import Bookhound.Parsers.Char      (alpha, alphaNum, char, colon, dot, lower,+                                    newLine, quote, underscore, upper)+import Bookhound.Parsers.Number    (double, int)+import Bookhound.Parsers.String    (spacing, withinDoubleQuotes, withinParens,+                                    withinQuotes)+import SyntaxTrees.Haskell.Common  (Class (..), Ctor (..), CtorOp (..),+                                    Literal (..), Module (..), QClass (QClass),+                                    QCtor (..), QCtorOp (..), QVar (..),+                                    QVarOp (..), Var (..), VarOp (..))+import Utils.Foldable              (wrapMaybe)+import Utils.String                (wrap, wrapBackQuotes, wrapQuotes)++++literal :: Parser Literal+literal = token $+      UnitLit <$ is "()"+  <|> BoolLit <$> (True <$ is "True" <|> False <$ is "False")+  <|> IntLit   . show <$> int+  <|> FloatLit . show <$> double+  <|> CharLit   <$> withinQuotes        (charLit   <|> charLitEscaped)+  <|> StringLit <$> withinDoubleQuotes ((stringLit <|> charLitEscaped) |*)++  where+    charLit = noneOf ['\'', '\\']+    charLitEscaped = read . wrapQuotes <$> (is '\\' ->>- alpha)+                     <|> (is '\\' *> char)+    stringLit = noneOf ['"', '\\']++++var :: Parser Var+var = Var <$> notReserved+              (withinParens (operator opSymbol <|> simpleOperator <|> simpleOperatorFn)+               <|> ident lower)++ctor :: Parser Ctor+ctor = Ctor <$> notReserved+                (withinParens (operator colon) <|> ident upper)++varOp :: Parser VarOp+varOp = VarOp <$> notReserved+                 (wrapBackQuotes <$> withinBackQuotes (ident lower)+                  <|> (operator opSymbol <|> simpleOperator))++ctorOp :: Parser CtorOp+ctorOp = CtorOp <$> notReserved+                    (wrapBackQuotes <$> withinBackQuotes (ident upper)+                     <|> operator colon)++class' :: Parser Class+class' = Class <$> ident upper++module' :: Parser Module+module' = Module <$> someSepBy dot (ident upper)++module'' :: Parser Module+module'' = Module <$> someSepBy dot (nonTokenIdent upper)++qVar :: Parser QVar+qVar = uncurry QVar <$> qTerm var++qCtor :: Parser QCtor+qCtor = uncurry QCtor <$> qTerm' Ctor++qVarOp :: Parser QVarOp+qVarOp = uncurry QVarOp <$> qTerm varOp++qCtorOp :: Parser QCtorOp+qCtorOp = uncurry QCtorOp <$> qTerm ctorOp++qClass :: Parser QClass+qClass = uncurry QClass <$> qTerm' Class++++ident :: Parser Char -> Parser String+ident start = token $ (:) <$> start <*> (idChar |*)++operator :: Parser Char -> Parser String+operator start = token $ (:) <$> start+                             <*> ((opSymbol <|> colon) |*)++simpleOperator :: Parser String+simpleOperator = token $ oneOf [":"]++simpleOperatorFn :: Parser String+simpleOperatorFn = token $ oneOf [",", ",,", ",,,"]++nonTokenQVar :: Parser QVar+nonTokenQVar = uncurry QVar <$> qTerm x+  where  x = Var <$> check "" (`notElem` reservedKeyWords)+                    (nonTokenIdent lower)++nonTokenIdent :: Parser Char -> Parser String+nonTokenIdent start = (:) <$> start <*> (idChar |*)+++idChar :: Parser Char+idChar = alphaNum <|> underscore <|> quote++opSymbol :: Parser Char+opSymbol = oneOf symbolChars++token :: Parser a -> Parser a+token = withTransform $ maybeWithin (anyComment |+) . maybeWithin spacing+++qTerm :: Parser a -> Parser (Maybe Module, a)+qTerm x =  (,) <$> ((module'' <* dot) |?) <*> x+++qTerm' :: (String -> b) -> Parser (Maybe Module, b)+qTerm' fn = token parser+  where+    parser = do xs <- getComponents <$> module''+                pure $ (Module <$> wrapMaybe (init xs), fn $ last xs)+    getComponents (Module xs) = xs+++anyComment :: Parser String+anyComment = pragma <|> blockComment <|> lineComment++lineComment :: Parser String+lineComment = is "--" ->>- (pure <$> newLine <|>+                          noneOf symbolChars ->>- (inverse newLine |*))+++blockComment :: Parser String+blockComment = wrap "{-"  "-}" . fold <$> withinBoth (is "{-") (is "-}")+                         ((:) <$> (isNot "#") <*> ((isNot "-" ->>- isNot "}") |*))+++pragma :: Parser String+pragma = wrap "{-#"  "#-}" . fold <$> withinBoth (is "{-#") (is "#-}")+                             ((isNot "#" |*))++symbolChars :: [Char]+symbolChars =+     ['!', '#', '$', '%', '&', '*', '+', '.', '/',+      '<', '=', '>', '?', '@', '\\', '|', '^', '|',+      '-', '~']+++notReserved :: Parser String -> Parser String+notReserved = check "reserved"+               (`notElem` (reservedSymbols ++ reservedKeyWords))+++reservedKeyWords :: [String]+reservedKeyWords = ["case","class","data","default","deriving",+                    "do","else","forall" ,"if","import","in",+                    "infix","infixl","infixr","instance",+                    "let","module" ,"newtype","of","qualified",+                    "then","type","where","_" ,"foreign",+                    "ccall","as","safe","unsafe"]++reservedSymbols :: [String]+reservedSymbols = ["..","::","=","\\","|","<-","->","@","~","=>","[","]"]+++withinBackQuotes :: Parser b -> Parser b+withinBackQuotes = within (is '`')
+ src/Parsers/Haskell/DataDef.hs view
@@ -0,0 +1,75 @@+module Parsers.Haskell.DataDef where++import Parsers.Haskell.Common      (class', ctor, var)+import Parsers.Haskell.Type        (anyKindedType, type', typeCtor, typeParam)+import SyntaxTrees.Haskell.DataDef (DataCtorDef (..), DataDef (..),+                                    DerivingClause (..), DerivingStrategy (..),+                                    FieldDef (..), NamedFieldDef (..),+                                    NewTypeDef (..), TypeDef (..),+                                    UnNamedFieldDef (..))++import Bookhound.Parser              (Parser, withError)+import Bookhound.ParserCombinators   (IsMatch (..), anySepBy, someSepBy, (<#>),+                                      (<|>), (|*), (|?))+import Bookhound.Parsers.Char        (colon, comma, equal)+import Bookhound.Parsers.Collections (tupleOf)+import Bookhound.Parsers.String      (maybeWithinParens, withinCurlyBrackets,+                                      withinParens)++import Data.Foldable (Foldable (fold))+++typeDef :: Parser TypeDef+typeDef = withError "Type declaration" $+  TypeDef <$> ((is "type") *> typeCtor)+          <*> (typeParam |*) <* equal+          <*> anyKindedType++newtypeDef :: Parser NewTypeDef+newtypeDef = withError "Newtype declaration" $+  NewTypeDef <$> (is "newtype" *> typeCtor)+             <*> (typeParam |*) <* equal+             <*> ctor+             <*> fieldDef+             <*> (derivingClause |*)++dataDef :: Parser DataDef+dataDef = withError "Data declaration" $+  DataDef <$> (is "data" *> typeCtor)+          <*> (typeParam |*)+          <*> (fold <$> alternatives)+          <*> (derivingClause |*)+  where+    alternatives = ((equal *> someSepBy (is "|") dataCtorDef) |?)+++namedFieldDef :: Parser NamedFieldDef+namedFieldDef = NamedFieldDef <$> var <* (colon <#> 2)+                              <*> type'++unNamedFieldDef :: Parser UnNamedFieldDef+unNamedFieldDef = UnNamedFieldDef <$> (withinParens type' <|> type')++fieldDef :: Parser FieldDef+fieldDef = UnNamedField <$> unNamedFieldDef <|>+           NamedField   <$> withinCurlyBrackets namedFieldDef++dataCtorDef :: Parser DataCtorDef+dataCtorDef = NamedFieldsCtor   <$> ctor+                                <*> (withinCurlyBrackets $+                                    anySepBy comma namedFieldDef) <|>+              UnNamedFieldsCtor <$> ctor+                                <*> (unNamedFieldDef |*)++derivingClause :: Parser DerivingClause+derivingClause = (is "deriving" *>+                  ((is "stock" |?) *>+                      (Deriving StandardDeriving <$> derivingList))+                  <|> (is "newtype" *>+                       (Deriving NewTypeDeriving <$> derivingList))+                  <|> (is "anyclass" *>+                       (Deriving AnyClassDeriving <$> derivingList))+                  <|> (DerivingVia <$> derivingList+                                   <*> (is "via" *> anyKindedType)))+  where+    derivingList = (tupleOf class' <|> pure <$> maybeWithinParens class')
+ src/Parsers/Haskell/FnDef.hs view
@@ -0,0 +1,207 @@+module Parsers.Haskell.FnDef where++import Lexers.Haskell.Layout     (lexeme)+import Parsers.Haskell.Common    (literal, nonTokenQVar, qCtor, qCtorOp, qVar,+                                  qVarOp, token, var, varOp)+import Parsers.Haskell.Pattern   (pattern')+import Parsers.Haskell.Type      (type')+import SyntaxTrees.Haskell.FnDef (Associativity (LAssoc, RAssoc),+                                  CaseBinding (..), DoStep (..), FnBody (..),+                                  FnDef (FnDef), FnDefOrSig (..), FnOp (..),+                                  FnSig (..), FnVar (..), Guard (..),+                                  GuardedFnBody (..),+                                  InfixFnAnnotation (InfixFnAnnotation),+                                  MaybeGuardedFnBody (..), PatternGuard (..))++import Bookhound.Parser              (Parser, andThen, check, withError)+import Bookhound.ParserCombinators   (IsMatch (is), someSepBy, (->>-), (<|>),+                                      (|*), (|+), (|?))+import Bookhound.Parsers.Char        (comma, dot)+import Bookhound.Parsers.Collections (listOf, tupleOf)+import Bookhound.Parsers.Number      (int)+import Bookhound.Parsers.String      (spacing, string, withinCurlyBrackets,+                                      withinParens, withinSquareBrackets)++import Data.Foldable (Foldable (fold))+import Data.Maybe    (maybeToList)+import Utils.String  (wrapCurly)+++fnSig :: Parser FnSig+fnSig = withError "Function signature" $+  FnSig <$> (var <* is "::")+        <*> type'+++fnDef :: Parser FnDef+fnDef = withError "Function definition" $+  FnDef <$> (tupleOf var <|> pure <$> var)+        <*> (pattern' |*)+        <*> maybeGuardedFnBody (is "=")+++infixAnnotation :: Parser InfixFnAnnotation+infixAnnotation = withError "Infix annotation" $+  InfixFnAnnotation <$> token (LAssoc <$ is "infixl" <|>+                               RAssoc <$ is "infixr")+                    <*> token int+                    <*> varOp+++fnDefOrSig :: Parser FnDefOrSig+fnDefOrSig =  Def <$> fnDef <|>+              Sig <$> fnSig++fnBody :: Parser FnBody+fnBody = topLevelFnApply <|> openForm++  where+    topLevelFnApply = FnApply <$> delimitedForm+                              <*> (pure <$> lambdaExpr)++    fnApply = FnApply <$> delimitedForm+                      <*> (delimitedForm |+)++    infixFnApply = uncurry InfixFnApply <$>+      sepByOps fnOp (infixArgForm <|> withinParens typeAnnotation)++    leftOpSection = uncurry LeftOpSection+      <$> withinParens ((,) <$> fnOp <*> openForm)++    rightOpSection = uncurry RightOpSection+      <$> withinParens ((,) <$> openForm <*> fnOp)++    opSection = leftOpSection <|> rightOpSection+++    lambdaExpr = LambdaExpr <$> (is '\\' *> (pattern' |*))+                            <*> (is "->" *> openForm)++    letExpr = LetExpr <$> (is "let" *> withinContext fnDefOrSig)+                      <*> (is "in"  *> openForm)++    whereExpr = WhereExpr <$> withinCurlyBrackets openForm <* is "where"+                          <*> withinContext fnDefOrSig++    ifExpr = IfExpr <$> (is "if"   *> openForm)+                    <*> (is "then" *> openForm)+                    <*> (is "else" *> openForm)++    multiWayIfExpr = MultiWayIfExpr <$>+      (is "if" *> (withinContext $ guardedFnBody $ is "->"))++    doExpr = DoExpr <$> (is "do" *> withinContext doStep)++    caseOfExpr = CaseOfExpr <$> (is "case" *> openForm <* is "of")+                            <*> withinContext caseBinding++    lambdaCaseExpr = LambdaCaseExpr <$> (is "\\case" *> withinContext caseBinding)++    listRange = withinSquareBrackets $+      ListRange <$> (openForm <* is "..")+                <*> (openForm |?)++    typeAnnotation = TypeAnnotation <$> (infixArgForm <* is "::")+                                    <*> type'++    tuple = Tuple <$> tupleOf openForm++    list = List <$> listOf openForm++    fnOp = CtorOp' <$> qCtorOp+       <|> VarOp' <$> qVarOp++    fnOp' = FnOp' <$> withinParens fnOp++    fnVar = FnVar' . Selector <$> withinParens (dot *> var)+        <|> FnVar' <$>+            (Selection <$> nonTokenQVar <* dot <*> someSepBy dot var)+        <|> FnVar' . Var' <$> qVar+        <|> FnVar' . Ctor' <$> qCtor++    literal' = Literal' <$> literal++    recordCreate = RecordCreate <$> delimitedForm <*> recordFields++    recordUpdate = RecordUpdate <$> delimitedForm <*> recordFields++    recordFields = withinCurlyBrackets (someSepBy comma recordField)++    recordField  = (,) <$> var <*> (is "=" *> openForm)++    infixArgForm = complexInfixForm <|> withinParens complexInfixForm+               <|> singleForm++    openForm = complexForm <|> singleForm+               <|> withinParens (complexForm <|> singleForm)++    delimitedForm = singleForm <|> withinParens complexForm+                    <|> withinParens singleForm++    singleForm = fnOp' <|> fnVar <|> literal' <|> tuple <|>+                 listRange <|> list <|> opSection++    complexForm = infixFnApply <|> complexInfixForm <|> typeAnnotation+++    complexInfixForm = fnApply <|> lambdaCaseExpr <|>+                       lambdaExpr <|> letExpr <|> whereExpr <|>+                       ifExpr <|> multiWayIfExpr <|> doExpr <|>+                       caseOfExpr <|> withinParens infixFnApply <|>+                       recordCreate <|> recordUpdate+++doStep :: Parser DoStep+doStep = DoBinding  <$> (tupleOf var <|> pure <$> var) <* is "<-"+                    <*> (adaptFnBody `andThen` fnBody) <|>+         LetBinding <$> (is "let" *> withinContext fnDefOrSig) <|>+         Body       <$> (adaptFnBody `andThen` fnBody)+++caseBinding :: Parser CaseBinding+caseBinding = CaseBinding <$> pattern' <*> maybeGuardedFnBody (is "->")+++maybeGuardedFnBody :: Parser a -> Parser MaybeGuardedFnBody+maybeGuardedFnBody sep = Guarded  <$> (guardedFnBody sep |+) <|>+                         Standard <$> (sep *> (adaptFnBody `andThen` fnBody))++guardedFnBody :: Parser a -> Parser GuardedFnBody+guardedFnBody sep = GuardedFnBody <$> guard <* sep <*> (adaptFnBody `andThen` fnBody)++guard :: Parser Guard+guard = Otherwise <$  (is "|" *> token (is "otherwise")) <|>+        Guard     <$> (is "|" *> someSepBy comma patternGuard)+++patternGuard :: Parser PatternGuard+patternGuard = PatternGuard <$> (pattern' <* is "<-") <*> fnBody <|>+               SimpleGuard  <$> fnBody+++adaptFnBody :: Parser String+adaptFnBody = do start <- otherText+                 next <- ((is "where" ->>- string) |?)+                 other <- ((is ";" ->>- string) |?)+                 let x = maybe start ((wrapCurly start) ++) next ++ fold other+                 pure x+ where+   otherText = (spacing |?) ->>- (textElem |*)+   textElem = check "" (`notElem` ["where", ";"]) lexeme ->>- (spacing |?)+++statements :: Parser a -> Parser [a]+statements parser = fold <$> someSepBy (is ";") (maybeToList <$> (parser |?))++withinContext :: Parser a -> Parser [a]+withinContext = withinCurlyBrackets . statements++withinContextTupled :: Parser a1 -> Parser a2 -> Parser ([a1], [a2])+withinContextTupled p1 p2 = withinCurlyBrackets $+                             (,) <$> statements p1 <*> statements p2+++sepByOps :: Parser a -> Parser b -> Parser ([a], [b])+sepByOps sep p = do x <-  p+                    y <- (((,) <$> sep <*> p) |+)+                    pure $ (fst <$> y, x : (snd <$> y))
+ src/Parsers/Haskell/ModuleDef.hs view
@@ -0,0 +1,84 @@+module Parsers.Haskell.ModuleDef where+++import Parsers.Haskell.ClassDef (classDef, derivingDef, instanceDef)+import Parsers.Haskell.Common   (module', token, var, varOp)+import Parsers.Haskell.DataDef  (dataDef, newtypeDef, typeDef)+import Parsers.Haskell.FnDef    (fnDef, fnSig, infixAnnotation,+                                 withinContextTupled)+import Parsers.Haskell.Type     (typeVar)++import SyntaxTrees.Haskell.FnDef     (FnDefOrSig (..))+import SyntaxTrees.Haskell.ModuleDef (ImportExportDef (..), InternalDef (..),+                                      ModuleDef (..), ModuleExport (..),+                                      ModuleExportDef (..), ModuleImport (..),+                                      ModuleImportDef (..), ModuleMember (..))++import Bookhound.Parser            (Parser)+import Bookhound.ParserCombinators (IsMatch (is), anySepBy, maybeWithin, (<|>),+                                    (|?))+import Bookhound.Parsers.Char      (comma)+import Bookhound.Parsers.String    (spacing, withinParens)+++import Data.Foldable (Foldable (fold))+import Data.Maybe    (isJust)++++moduleDef :: Parser ModuleDef+moduleDef = uncurry <$>+              (ModuleDef <$> (is "module" *> module')+                         <*> (moduleExport |?)+                         <*  is "where")+                         <*> withinContextTupled moduleImport internalDef++++moduleExport :: Parser ModuleExport+moduleExport = ModuleExport <$> withinParens (anySepBy comma moduleExportDef)+++moduleExportDef :: Parser ModuleExportDef+moduleExportDef = ModuleExportDef  <$> importExportDef <|>+                  FullModuleExport <$> (is "module" *> module')++moduleImport :: Parser ModuleImport+moduleImport = ModuleImport <$> (token (is "import") *>+                                 (isJust <$> (is "qualified" |?)))+                            <*> module'+                            <*> ((is "as" *> module') |?)+                            <*> (isJust <$> (is "hiding" |?))+                            <*> (fold <$> (defs |?))+  where+    defs = withinParens $ anySepBy comma $ maybeWithin spacing moduleImportDef+++moduleImportDef :: Parser ModuleImportDef+moduleImportDef = ModuleImportDef <$> importExportDef+++importExportDef :: Parser ImportExportDef+importExportDef = FullData     <$> typeVar+                               <*  withinParens (is "..")      <|>+                  FilteredData <$> typeVar+                               <*> withinParens+                                 (anySepBy comma moduleMember) <|>+                  Member       <$> moduleMember+++moduleMember :: Parser ModuleMember+moduleMember = VarOpMember <$> withinParens varOp <|>+               VarMember   <$> var                <|>+               DataMember  <$> typeVar++internalDef :: Parser InternalDef+internalDef = FnDefOrSig' . Def  <$> fnDef        <|>+              FnDefOrSig' . Sig  <$> fnSig        <|>+              TypeDef'           <$> typeDef      <|>+              NewTypeDef'        <$> newtypeDef   <|>+              DataDef'           <$> dataDef      <|>+              ClassDef'          <$> classDef     <|>+              InstanceDef'       <$> instanceDef  <|>+              DerivingDef'       <$> derivingDef  <|>+              InfixFnAnnotation' <$> infixAnnotation
+ src/Parsers/Haskell/Pattern.hs view
@@ -0,0 +1,49 @@+module Parsers.Haskell.Pattern where++import Parsers.Haskell.Common      (literal, qCtor, qCtorOp, token, var)+import SyntaxTrees.Haskell.Pattern (Pattern (..))++import Bookhound.Parser              (Parser)+import Bookhound.ParserCombinators   (IsMatch (is), anySepBy, sepByOp, (<|>),+                                      (|+), (|?))+import Bookhound.Parsers.Char        (comma, underscore)+import Bookhound.Parsers.Collections (listOf, tupleOf)+import Bookhound.Parsers.String      (maybeWithinParens, withinCurlyBrackets,+                                      withinParens)++++pattern' :: Parser Pattern+pattern' =  pattern'' <|> maybeWithinParens pattern''+  where+    ctor'       = CtorPattern <$> qCtor <*> (ctorElem' |+)+    nullaryCtor = CtorPattern <$> qCtor <*> pure []+    infixCtor   = uncurry InfixCtorPattern <$> sepByOp qCtorOp (ctor' <|> ctorElem')++    record = RecordPattern <$> qCtor <*> recordShape+    recordWildcard = WildcardRecordPattern <$> qCtor+                                           <*> wildcardRecordShape++    alias    = AliasedPattern <$> (var <* is "@") <*> aliasElem'+    var'     = VarPattern <$> var+    literal' = LitPattern <$> literal+    wildcard = Wildcard <$ token underscore++    list          = ListPattern <$> listOf pattern'+    tuple         = TuplePattern <$> (tupleOf pattern')+    recordField   = (,) <$> var <*> ((is "=" *> pattern'') |?)+    recordShape = withinCurlyBrackets (anySepBy comma recordField)+    wildcardRecordShape =+      withinCurlyBrackets (anySepBy comma recordField <* token comma <* is "..")++    elem' =  literal' <|> var' <|> alias <|> wildcard <|> nullaryCtor <|>+            withinParens nullaryCtor <|>+            tuple <|> list++    ctorElem' = record <|> recordWildcard <|> alias <|> elem' <|>+                withinParens (ctor' <|> infixCtor)++    aliasElem' = elem' <|> record <|> recordWildcard <|>+                 withinParens (ctor' <|> infixCtor)++    pattern'' = alias <|> infixCtor <|> ctor' <|> ctorElem'
+ src/Parsers/Haskell/Type.hs view
@@ -0,0 +1,86 @@+module Parsers.Haskell.Type where+++import Bookhound.Parser              (Parser)+import Bookhound.ParserCombinators   (IsMatch (is), multipleSepBy, (<|>),+                                      (|+))+import Bookhound.Parsers.Char        (comma, dot, lower, upper)+import Bookhound.Parsers.Collections (tupleOf)+import Bookhound.Parsers.String      (maybeWithinParens, withinParens,+                                      withinSquareBrackets)++import Parsers.Haskell.Common   (ident, notReserved, qClass, qTerm')+import SyntaxTrees.Haskell.Type (AnyKindedType (..), ClassConstraint (..),+                                 QTypeCtor (QTypeCtor), QTypeVar (QTypeVar),+                                 Type (..), TypeCtor (..), TypeParam (..),+                                 TypeVar (..))++typeParam :: Parser TypeParam+typeParam = TypeParam <$> notReserved (ident lower)++typeVar :: Parser TypeVar+typeVar = TypeVar  <$> ident upper <|>+          UnitType <$ is "()"++typeCtor :: Parser TypeCtor+typeCtor = TypeCtor  <$> ident upper <|>+           Arrow     <$  is "(->)"   <|>+           TupleType <$  is "(,)"    <|>+           ListType  <$  is "[]"++anyKindedType :: Parser AnyKindedType+anyKindedType = TypeValue <$> type'     <|>+                TypeFn    <$> qTypeCtor+++classConstraints :: Parser Type -> Parser [ClassConstraint]+classConstraints typeParser =+  tupleOf (classConstraint typeParser)+  <|> pure <$> maybeWithinParens (classConstraint typeParser)+++classConstraint :: Parser Type -> Parser ClassConstraint+classConstraint typeParser = ClassConstraint <$> qClass <*> (typeParser |+)++++type' :: Parser Type+type' = typeScope <|> classScope <|> type'' <|> maybeWithinParens (type'')+  where+    type'' = arrow <|> typeApply <|> elem'++    typeApply = CtorTypeApply   <$> typeCtor' <*> (typeApplyElem |+) <|>+                ParamTypeApply  <$> typeParam <*> (typeApplyElem |+) <|>+                NestedTypeApply <$> withinParens typeApply <*> (typeApplyElem |+)++    arrow = CtorTypeApply (QTypeCtor Nothing Arrow)+            <$> multipleSepBy (is "->") arrowElem+    tuple = CtorTypeApply (QTypeCtor Nothing TupleType)+            <$> (withinParens $ multipleSepBy comma type'')+    list  = CtorTypeApply (QTypeCtor Nothing ListType)+            <$> (pure <$> withinSquareBrackets type'')++    typeCtor'  = qTypeCtor <|> QTypeCtor Nothing <$> typeCtor+    typeVar'   = TypeVar'   <$> (qTypeVar <|> QTypeVar Nothing <$> typeVar)+    typeParam' = TypeParam' <$> typeParam++    typeScope = TypeScope <$> (is "forall" *> (typeParam |+) <* dot)+                          <*> (classScope <|> type'')+    classScope = ClassScope <$> (classConstraints' <* (is "=>"))+                            <*> type''++    classConstraints' = classConstraints+                        (elem' <|> withinParens (arrow <|> typeApply))+++    typeApplyElem = elem' <|> withinParens (arrow <|> typeApply)+    arrowElem     = typeApply <|> elem' <|> withinParens arrow++    elem' = typeVar' <|> typeParam' <|> tuple <|> list <|>+            withinParens (typeScope <|> classScope)++qTypeVar :: Parser QTypeVar+qTypeVar = uncurry QTypeVar <$> qTerm' TypeVar++qTypeCtor :: Parser QTypeCtor+qTypeCtor = uncurry QTypeCtor <$> qTerm' TypeCtor
+ src/SyntaxTrees/Haskell/ClassDef.hs view
@@ -0,0 +1,35 @@+module SyntaxTrees.Haskell.ClassDef where++import SyntaxTrees.Haskell.Common  (Class)+import SyntaxTrees.Haskell.DataDef (DerivingStrategy)+import SyntaxTrees.Haskell.FnDef   (FnDefOrSig)+import SyntaxTrees.Haskell.Type    (AnyKindedType, ClassConstraint, TypeParam)+++data ClassDef+  = ClassDef+      { constraints :: [ClassConstraint]+      , name        :: Class+      , typeParams  :: [TypeParam]+      , defs        :: [FnDefOrSig]+      }+  deriving (Show)++data InstanceDef+  = InstanceDef+      { constraints :: [ClassConstraint]+      , class'      :: Class+      , types       :: [AnyKindedType]+      , defs        :: [FnDefOrSig]+      }+  deriving (Show)++data DerivingDef+  = DerivingDef+      { strategy    :: DerivingStrategy+      , constraints :: [ClassConstraint]+      , class'      :: Class+      , types       :: [AnyKindedType]+      , derivingVia :: Maybe Class+      }+  deriving (Show)
+ src/SyntaxTrees/Haskell/Common.hs view
@@ -0,0 +1,56 @@+module SyntaxTrees.Haskell.Common where+++newtype Var+  = Var String+  deriving (Eq, Show)++newtype Ctor+  = Ctor String+  deriving (Eq, Show)++newtype VarOp+  = VarOp String+  deriving (Eq, Show)++newtype CtorOp+  = CtorOp String+  deriving (Eq, Show)++newtype Class+  = Class String+  deriving (Eq, Show)++newtype Module+  = Module [String]+  deriving (Eq, Show)++data Literal+  = UnitLit+  | BoolLit Bool+  | IntLit String+  | FloatLit String+  | CharLit Char+  | StringLit String+  deriving (Eq, Show)+++data QVar+  = QVar (Maybe Module) Var+  deriving (Eq, Show)++data QCtor+  = QCtor (Maybe Module) Ctor+  deriving (Eq, Show)++data QVarOp+  = QVarOp (Maybe Module) VarOp+  deriving (Eq, Show)++data QCtorOp+  = QCtorOp (Maybe Module) CtorOp+  deriving (Eq, Show)++data QClass+  = QClass (Maybe Module) Class+  deriving (Eq, Show)
+ src/SyntaxTrees/Haskell/DataDef.hs view
@@ -0,0 +1,77 @@+module SyntaxTrees.Haskell.DataDef where++import SyntaxTrees.Haskell.Common (Class, Ctor, Var)+import SyntaxTrees.Haskell.Type   (AnyKindedType, Type, TypeCtor, TypeParam)+++data TypeDef+  = TypeDef+      { alias      :: TypeCtor+      , typeParams :: [TypeParam]+      , type'      :: AnyKindedType+      }+  deriving (Show)++data NewTypeDef+  = NewTypeDef+      { type'      :: TypeCtor+      , typeParams :: [TypeParam]+      , ctor       :: Ctor+      , field      :: FieldDef+      , deriving'  :: [DerivingClause]+      }+  deriving (Show)++data DataDef+  = DataDef+      { type'      :: TypeCtor+      , typeParams :: [TypeParam]+      , ctorDefs   :: [DataCtorDef]+      , deriving'  :: [DerivingClause]+      }+  deriving (Show)++data DataCtorDef+  = UnNamedFieldsCtor+      { ctor          :: Ctor+      , unnamedFields :: [UnNamedFieldDef]+      }+  | NamedFieldsCtor+      { ctor        :: Ctor+      , namedFields :: [NamedFieldDef]+      }+  deriving (Show)++data FieldDef+  = UnNamedField UnNamedFieldDef+  | NamedField NamedFieldDef+  deriving (Show)++data UnNamedFieldDef+  = UnNamedFieldDef+      { type' :: Type+      }+  deriving (Show)++data NamedFieldDef+  = NamedFieldDef+      { name  :: Var+      , type' :: Type+      }+  deriving (Show)++data DerivingClause+  = Deriving DerivingStrategy [Class]+  | DerivingVia [Class] AnyKindedType+  deriving (Show)++data DerivingStrategy+  = StandardDeriving+  | NewTypeDeriving+  | AnyClassDeriving+  deriving (Eq, Show)+++derivingClasses :: DerivingClause -> [(DerivingStrategy, Class)]+derivingClasses (Deriving x y)    = (x,) <$> y+derivingClasses (DerivingVia x _) = (StandardDeriving,) <$> x
+ src/SyntaxTrees/Haskell/FnDef.hs view
@@ -0,0 +1,149 @@+module SyntaxTrees.Haskell.FnDef where++import SyntaxTrees.Haskell.Common  (Literal, QCtor, QCtorOp, QVar, QVarOp, Var,+                                    VarOp)+import SyntaxTrees.Haskell.Pattern (Pattern)+import SyntaxTrees.Haskell.Type    (Type)++++data FnSig+  = FnSig+      { name  :: Var+      , type' :: Type+      }+  deriving (Show)++data FnDef+  = FnDef+      { names :: [Var]+      , args  :: [Pattern]+      , body  :: MaybeGuardedFnBody+      }+  deriving (Show)++data InfixFnAnnotation+  = InfixFnAnnotation+      { associativity :: Associativity+      , precedence    :: Integer+      , name          :: VarOp+      }+  deriving (Show)++data FnDefOrSig+  = Def FnDef+  | Sig FnSig+  deriving (Show)++data FnBody+  = FnApply+      { fn   :: FnBody+      , args :: [FnBody]+      }+  | InfixFnApply+      { fnOps :: [FnOp]+      , args  :: [FnBody]+      }+  | LeftOpSection+      { fnOp :: FnOp+      , arg  :: FnBody+      }+  | RightOpSection+      { arg  :: FnBody+      , fnOp :: FnOp+      }+  | LambdaExpr+      { patterns :: [Pattern]+      , body     :: FnBody+      }+  | LetExpr+      { fnBindings :: [FnDefOrSig]+      , body       :: FnBody+      }+  | WhereExpr+      { body       :: FnBody+      , fnBindings :: [FnDefOrSig]+      }+  | IfExpr+      { cond       :: FnBody+      , ifBranch   :: FnBody+      , elseBranch :: FnBody+      }+  | MultiWayIfExpr+      { whenExprs :: [GuardedFnBody]+      }+  | DoExpr+      { steps :: [DoStep]+      }+  | CaseOfExpr+      { matchee :: FnBody+      , cases   :: [CaseBinding]+      }+  | LambdaCaseExpr+      { cases :: [CaseBinding]+      }+  | RecordCreate+      { ctor        :: FnBody+      , namedFields :: [(Var, FnBody)]+      }+  | RecordUpdate+      { var         :: FnBody+      , namedFields :: [(Var, FnBody)]+      }+  | TypeAnnotation FnBody Type+  | ListRange FnBody (Maybe FnBody)+  | Tuple [FnBody]+  | List [FnBody]+  | FnVar' FnVar+  | FnOp' FnOp+  | Literal' Literal+  deriving (Show)++data FnVar+  = Selector Var+  | Selection QVar [Var]+  | Var' QVar+  | Ctor' QCtor+  deriving (Show)++data FnOp+  = VarOp' QVarOp+  | CtorOp' QCtorOp+  deriving (Show)++data DoStep+  = DoBinding [Var] FnBody+  | LetBinding [FnDefOrSig]+  | Body FnBody+  deriving (Show)++data CaseBinding+  = CaseBinding Pattern MaybeGuardedFnBody+  deriving (Show)++data MaybeGuardedFnBody+  = Guarded [GuardedFnBody]+  | Standard FnBody+  deriving (Show)++data GuardedFnBody+  = GuardedFnBody+      { guard :: Guard+      , body  :: FnBody+      }+  deriving (Show)++data Guard+  = Guard [PatternGuard]+  | Otherwise+  deriving (Show)++data PatternGuard+  = PatternGuard Pattern FnBody+  | SimpleGuard FnBody+  deriving (Show)++data Associativity+  = LAssoc+  | RAssoc+  deriving (Show)
+ src/SyntaxTrees/Haskell/ModuleDef.hs view
@@ -0,0 +1,64 @@+module SyntaxTrees.Haskell.ModuleDef where++import SyntaxTrees.Haskell.ClassDef (ClassDef, DerivingDef, InstanceDef)+import SyntaxTrees.Haskell.Common   (Module, Var, VarOp)+import SyntaxTrees.Haskell.DataDef  (DataDef, NewTypeDef, TypeDef)+import SyntaxTrees.Haskell.FnDef    (FnDefOrSig, InfixFnAnnotation)+import SyntaxTrees.Haskell.Type     (TypeVar)+++data ModuleDef+  = ModuleDef+      { name    :: Module+      , export  :: Maybe ModuleExport+      , imports :: [ModuleImport]+      , defs    :: [InternalDef]+      }+  deriving (Show)++newtype ModuleExport+  = ModuleExport [ModuleExportDef]+  deriving (Show)++data ModuleExportDef+  = ModuleExportDef ImportExportDef+  | FullModuleExport Module+  deriving (Show)++data ModuleImport+  = ModuleImport+      { qualified  :: Bool+      , module'    :: Module+      , alias      :: Maybe Module+      , hiding     :: Bool+      , importDefs :: [ModuleImportDef]+      }+  deriving (Show)++data ModuleImportDef+  = ModuleImportDef ImportExportDef+  deriving (Show)++data ImportExportDef+  = Member ModuleMember+  | FullData TypeVar+  | FilteredData TypeVar [ModuleMember]+  deriving (Show)++data ModuleMember+  = VarMember Var+  | VarOpMember VarOp+  | DataMember TypeVar+  deriving (Show)++data InternalDef+  = TypeDef' TypeDef+  | NewTypeDef' NewTypeDef+  | DataDef' DataDef+  | FnDefOrSig' FnDefOrSig+  | ClassDef' ClassDef+  | InstanceDef' InstanceDef+  | DerivingDef' DerivingDef+  | InfixFnAnnotation' InfixFnAnnotation+  deriving (Show)+
+ src/SyntaxTrees/Haskell/Pattern.hs view
@@ -0,0 +1,29 @@+module SyntaxTrees.Haskell.Pattern where++import SyntaxTrees.Haskell.Common (Literal, QCtor, QCtorOp, Var)+++data Pattern+  = CtorPattern+      { ctor   :: QCtor+      , fields :: [Pattern]+      }+  | InfixCtorPattern+      { ctorOp :: QCtorOp+      , fields :: [Pattern]+      }+  | RecordPattern+      { ctor        :: QCtor+      , namedFields :: [(Var, Maybe Pattern)]+      }+  | WildcardRecordPattern+      { ctor        :: QCtor+      , namedFields :: [(Var, Maybe Pattern)]+      }+  | AliasedPattern Var Pattern+  | ListPattern [Pattern]+  | TuplePattern [Pattern]+  | VarPattern Var+  | LitPattern Literal+  | Wildcard+  deriving (Show)
+ src/SyntaxTrees/Haskell/Type.hs view
@@ -0,0 +1,48 @@+module SyntaxTrees.Haskell.Type where++import SyntaxTrees.Haskell.Common (Module, QClass)+++newtype TypeParam+  = TypeParam String+  deriving (Eq, Ord, Show)++data TypeVar+  = TypeVar String+  | UnitType+  deriving (Show)++data TypeCtor+  = TypeCtor String+  | Arrow+  | TupleType+  | ListType+  deriving (Show)++data AnyKindedType+  = TypeValue Type+  | TypeFn QTypeCtor+  deriving (Show)++data ClassConstraint+  = ClassConstraint QClass [Type]+  deriving (Show)++data Type+  = CtorTypeApply QTypeCtor [Type]+  | ParamTypeApply TypeParam [Type]+  | NestedTypeApply Type [Type]+  | TypeVar' QTypeVar+  | TypeParam' TypeParam+  | TypeScope [TypeParam] Type+  | ClassScope [ClassConstraint] Type+  deriving (Show)+++data QTypeVar+  = QTypeVar (Maybe Module) TypeVar+  deriving (Show)++data QTypeCtor+  = QTypeCtor (Maybe Module) TypeCtor+  deriving (Show)
+ src/SyntaxTrees/Purescript/ClassDef.hs view
@@ -0,0 +1,73 @@+module SyntaxTrees.Purescript.ClassDef where++import Data.List                     (intercalate)+import Data.Monoid.HT                (when)+import SyntaxTrees.Purescript.Common (Class, Var)+import SyntaxTrees.Purescript.FnDef  (FnDefOrSig)+import SyntaxTrees.Purescript.Type   (AnyKindedType, ClassConstraint, TypeParam,+                                      showAnyKindedTypeNested)+import Utils.Foldable                (wrapMaybe)+import Utils.String                  (Wrapper (Wrapper), joinMaybePost,+                                      joinWords, str, wrapBlock, wrapParensCsv)+++data ClassDef+  = ClassDef+      { constraints :: [ClassConstraint]+      , name        :: Class+      , typeParams  :: [TypeParam]+      , defs        :: [FnDefOrSig]+      }++data InstanceDef+  = InstanceDef+      { constraints :: [ClassConstraint]+      , name        :: Maybe Var+      , class'      :: Class+      , types       :: [AnyKindedType]+      , defs        :: [FnDefOrSig]+      }++data DerivingDef+  = DerivingDef+      { strategy    :: DerivingStrategy+      , constraints :: [ClassConstraint]+      , name        :: Maybe Var+      , class'      :: Class+      , types       :: [AnyKindedType]+      }++data DerivingStrategy+  = StandardDeriving+  | NewTypeDeriving+  deriving (Eq)+++instance Show ClassDef where+  show (ClassDef x y z t) =+    joinWords ["class",+               (Wrapper <$> wrapMaybe (wrapParensCsv x))+                `joinMaybePost` "<=",+               show y,+               str " " z,+               wrapBlock t]++instance Show InstanceDef where+  show (InstanceDef x y z t u) =+    joinWords ["instance",+               (Wrapper <$> wrapMaybe (wrapParensCsv x))+                `joinMaybePost` "<=",+               y `joinMaybePost` "::",+               show z,+               intercalate " " $ showAnyKindedTypeNested <$> t,+               wrapBlock u]++instance Show DerivingDef where+  show (DerivingDef x y z t u) =+    joinWords ["derive",+               when (x == NewTypeDeriving) "newtype",+               "instance",+               (Wrapper <$> wrapMaybe (wrapParensCsv y)) `joinMaybePost` "<=",+               z `joinMaybePost` "::",+               show t,+               intercalate " " $ showAnyKindedTypeNested <$> u]
+ src/SyntaxTrees/Purescript/Common.hs view
@@ -0,0 +1,95 @@+module SyntaxTrees.Purescript.Common where++import Data.List (intercalate)+++newtype Var+  = Var String++newtype Ctor+  = Ctor String++newtype VarOp+  = VarOp String++newtype CtorOp+  = CtorOp String++newtype Class+  = Class String++newtype Module+  = Module [String]++data Literal+  = UnitLit+  | BoolLit Bool+  | IntLit String+  | NumberLit String+  | CharLit Char+  | StringLit String+++data QVar+  = QVar (Maybe Module) Var++data QCtor+  = QCtor (Maybe Module) Ctor++data QVarOp+  = QVarOp (Maybe Module) VarOp++data QCtorOp+  = QCtorOp (Maybe Module) CtorOp++data QClass+  = QClass (Maybe Module) Class++++instance Show Var where+  show (Var x) = x++instance Show Ctor where+  show (Ctor x) = x++instance Show VarOp where+  show (VarOp x) = x++instance Show CtorOp where+  show (CtorOp x) = x++instance Show Class where+  show (Class x) = x++instance Show Module where+  show (Module x) = intercalate "." x++instance Show Literal where+  show UnitLit         = "unit"+  show (BoolLit True)  = "true"+  show (BoolLit False) = "false"+  show (IntLit x)      = x+  show (NumberLit x)   = x+  show (CharLit x)     = show x+  show (StringLit x)   = show x+++instance Show QVar where+  show (QVar x y) = showQualified x y++instance Show QCtor where+  show (QCtor x y) = showQualified x y++instance Show QVarOp where+  show (QVarOp x y) = showQualified x y++instance Show QCtorOp where+  show (QCtorOp x y) = showQualified x y++instance Show QClass where+  show (QClass x y) = showQualified x y+++showQualified :: (Show a, Show b) => Maybe a -> b -> String+showQualified x y = foldMap ((++ ".") . show) x ++ show y
+ src/SyntaxTrees/Purescript/DataDef.hs view
@@ -0,0 +1,102 @@+module SyntaxTrees.Purescript.DataDef where++import SyntaxTrees.Purescript.Common (Ctor, Var)+import SyntaxTrees.Purescript.Type   (AnyKindedType, Type, TypeCtor, TypeParam,+                                      showTypeNested)+import Utils.String                  (joinWords, str, wrapCurlyCsv, wrapSpaces)+++data TypeDef+  = TypeDef+      { alias      :: TypeCtor+      , typeParams :: [TypeParam]+      , type'      :: AnyKindedType+      }++data NewTypeDef+  = NewTypeDef+      { type'      :: TypeCtor+      , typeParams :: [TypeParam]+      , ctor       :: Ctor+      , field      :: FieldDef+      }++data DataDef+  = DataDef+      { type'      :: TypeCtor+      , typeParams :: [TypeParam]+      , ctorDefs   :: [DataCtorDef]+      }++data DataCtorDef+  = UnNamedFieldsCtor+      { ctor          :: Ctor+      , unnamedFields :: [UnNamedFieldDef]+      }+  | NamedFieldsCtor+      { ctor        :: Ctor+      , namedFields :: [NamedFieldDef]+      }++data FieldDef+  = UnNamedField UnNamedFieldDef+  | NamedField NamedFieldDef++data UnNamedFieldDef+  = UnNamedFieldDef+      { type' :: Type+      }++data NamedFieldDef+  = NamedFieldDef+      { name  :: Var+      , type' :: Type+      }+++instance Show TypeDef where+  show (TypeDef x y z) =+    joinWords ["type",+               show x,+               str " " y,+               "=",+               show z]++instance Show NewTypeDef where+  show (NewTypeDef x y z t) =+    joinWords ["newtype",+               show x,+               str " " y,+               "=",+               show z,+               show t]++instance Show DataDef where+  show (DataDef x y z) =+    joinWords ["data",+               show x,+               str " " y,+               "=",+               str (wrapSpaces "|") z]++instance Show DataCtorDef where+  show (UnNamedFieldsCtor x y) =+    joinWords [show x,+               str " " y]++  show (NamedFieldsCtor x y) =+    joinWords [show x,+               wrapCurlyCsv y]++instance Show FieldDef where+  show (UnNamedField x) = show x+  show (NamedField x)   = show x++instance Show UnNamedFieldDef where+  show (UnNamedFieldDef x) = showTypeNested x++instance Show NamedFieldDef where+  show (NamedFieldDef x y) =+    joinWords [show x,+               "::",+               show y]
+ src/SyntaxTrees/Purescript/FnDef.hs view
@@ -0,0 +1,328 @@+module SyntaxTrees.Purescript.FnDef where++import Data.List                      (intercalate)+import SyntaxTrees.Purescript.Common  (Literal, QCtor, QCtorOp, QVar, QVarOp,+                                       Var, VarOp)+import SyntaxTrees.Purescript.Pattern (Pattern, showPatternNested)+import SyntaxTrees.Purescript.Type    (Type)+import Utils.List                     (mix)+import Utils.String                   (Wrapper (Wrapper), joinWords, str,+                                       wrapBlock, wrapContext, wrapCsv,+                                       wrapCurlyCsv, wrapParens, wrapParensCsv,+                                       wrapSpaces, wrapSquareCsv, (+++))++++data FnSig+  = FnSig+      { name  :: Var+      , type' :: Type+      }++data FnDef+  = FnDef+      { names :: [Var]+      , args  :: [Pattern]+      , body  :: MaybeGuardedFnBody+      }++data InfixFnDef+  = InfixFnDef+      { associativity :: Associativity+      , precedence    :: Integer+      , fnName        :: Var+      , opName        :: VarOp+      }++data FnDefOrSig+  = Def FnDef+  | Sig FnSig++data FnBody+  = FnApply+      { fn   :: FnBody+      , args :: [FnBody]+      }+  | InfixFnApply+      { fnOps :: [FnOp]+      , args  :: [FnBody]+      }+  | LeftOpSection+      { fnOp :: FnOp+      , arg  :: FnBody+      }+  | RightOpSection+      { arg  :: FnBody+      , fnOp :: FnOp+      }+  | LambdaExpr+      { patterns :: [Pattern]+      , body     :: FnBody+      }+  | LetExpr+      { fnBindings :: [FnDefOrSig]+      , body       :: FnBody+      }+  | WhereExpr+      { body       :: FnBody+      , fnBindings :: [FnDefOrSig]+      }+  | IfExpr+      { cond       :: FnBody+      , ifBranch   :: FnBody+      , elseBranch :: FnBody+      }+  | MultiWayIfExpr+      { whenExprs :: [GuardedFnBody]+      }+  | DoExpr+      { steps :: [DoStep]+      }+  | CaseOfExpr+      { matchee :: FnBody+      , cases   :: [CaseBinding]+      }+  | LambdaCaseExpr+      { cases :: [CaseBinding]+      }+  | RecordCreate+      { ctor        :: FnBody+      , namedFields :: [(Var, FnBody)]+      }+  | RecordUpdate+      { var         :: FnBody+      , namedFields :: [(Var, FnBody)]+      }+  | TypeAnnotation FnBody Type+  | ArrayRange FnBody FnBody+  | Tuple [FnBody]+  | Array [FnBody]+  | FnOp' FnOp+  | FnVar' FnVar+  | Literal' Literal++data FnVar+  = Selector Var+  | Selection QVar [Var]+  | Var' QVar+  | Ctor' QCtor++data FnOp+  = VarOp' QVarOp+  | CtorOp' QCtorOp++data DoStep+  = DoBinding [Var] FnBody+  | LetBinding [FnDefOrSig]+  | Body FnBody++data CaseBinding+  = CaseBinding Pattern MaybeGuardedFnBody++data MaybeGuardedFnBody+  = Guarded [GuardedFnBody]+  | Standard FnBody++data GuardedFnBody+  = GuardedFnBody+      { guard :: Guard+      , body  :: FnBody+      }++data Guard+  = Guard [PatternGuard]+  | Otherwise++data PatternGuard+  = PatternGuard Pattern FnBody+  | SimpleGuard FnBody++data Associativity+  = LAssoc+  | RAssoc+++instance Show FnSig where+  show (FnSig x y) =+    joinWords [show x,+               "::",+               show y]++instance Show FnDef where+  show (FnDef x y z) =+    joinWords [wrapCsv x,+               intercalate " " (showPatternNested <$> y),+               showMaybeGuardedFnBody "=" z]++instance Show InfixFnDef where+  show (InfixFnDef x y z t) =+    joinWords [show x,+               show y,+               show z,+               "as",+               show t]++instance Show FnDefOrSig where+  show (Def x) = show x+  show (Sig x) = show x++instance Show FnBody where++  show (FnApply fn args) =+    joinWords [showNestedFnBody fn,+               intercalate " " $ showNestedFnBody <$> args]++  show (InfixFnApply fnOps args) =+    intercalate "" $ mix (showNestedInfixFnBody <$> args)+                         (wrapSpaces . show <$> fnOps)++  show (LeftOpSection x y) =+    joinWords ["_",+              show x,+              showNestedFnBody y]++  show (RightOpSection x y) =+    joinWords [showNestedFnBody x,+               show y,+               "_"]++  show (LambdaExpr x y) =+    joinWords ["\\" ++ intercalate " " (showPatternNested <$> x),+               "->",+               show y]++  show (LetExpr x y) =+    "\n" ++ wrapContext ("let" ++ wrapBlock x ++ "in" ++ "\n" ++ show y)++  show (WhereExpr x y) =+    show x ++ "\n" ++ wrapContext ("where" ++ wrapBlock y)++  show (IfExpr x y z) =+    "if" +++ show x ++++    "then" ++ wrapBlock [y] ++ "\n" +++    "else" ++ wrapBlock [z]++  show (MultiWayIfExpr x) =+    "if" ++ wrapBlock (Wrapper . ("|" ++) .+            showGuardedFnBody "->" <$> x)++  show (DoExpr x) =+    "do" ++ wrapBlock x++  show (CaseOfExpr x y) =+    joinWords ["case",+              show x,+              "of",+              wrapBlock y]++  show (LambdaCaseExpr x) =+    "\\case" ++ wrapBlock x++  show (RecordCreate x y) =+    joinWords [show x,+               wrapCurlyCsv $ Wrapper . format <$> y]+    where+      format (z, t) = show z ++ ":" +++ show t++  show (RecordUpdate x y) =+    joinWords [show x,+               wrapCurlyCsv $ Wrapper . format <$> y]+    where+      format (z, t) = show z +++ "=" +++ show t++  show (TypeAnnotation x y) = joinWords [show x, "::", show y]+  show (ArrayRange x y) = joinWords [show x, "..", show y]+  show (Tuple x) = wrapParensCsv x+  show (Array x) = wrapSquareCsv x+  show (FnOp' x) = wrapParens $ show x+  show (FnVar' x) = show x+  show (Literal' x) = show x+++instance Show FnVar where+  show (Selector x)    = "." ++ show x+  show (Selection x y) = intercalate "." (show x : (show <$> y))+  show (Var' x)        = show x+  show (Ctor' x)       = show x++instance Show FnOp where+  show (VarOp' x)  = show x+  show (CtorOp' x) = show x++instance Show DoStep where++  show (DoBinding x y) =+    joinWords [wrapCsv x,+               "<-",+               show y]++  show (LetBinding x) = "let" ++ wrapBlock x++  show (Body x) = show x++instance Show CaseBinding where+  show (CaseBinding x y) =+    joinWords [show x,+               showMaybeGuardedFnBody "->" y]++instance Show Guard where+  show (Guard x)   = str ("\n" ++ ",") x+  show (Otherwise) = "otherwise"++instance Show PatternGuard where+  show (PatternGuard x y) =+    joinWords [show x,+               "<-",+               show y]+  show (SimpleGuard x) = show x++instance Show Associativity where+  show LAssoc = "infixl"+  show RAssoc = "infixr"+++showMaybeGuardedFnBody :: String -> MaybeGuardedFnBody -> String+showMaybeGuardedFnBody op (Guarded x) =+  wrapBlock $ Wrapper . ("|" ++) . showGuardedFnBody op <$> x+showMaybeGuardedFnBody op (Standard x) = op +++ show x++showGuardedFnBody :: String -> GuardedFnBody -> String+showGuardedFnBody op (GuardedFnBody x y) =+  joinWords [show x,+            op,+            show y]++showNestedFnBody :: FnBody -> String+showNestedFnBody x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      FnApply _ _        -> True+      InfixFnApply _ _   -> True+      LeftOpSection _ _  -> True+      RightOpSection _ _ -> True+      LambdaExpr _ _     -> True+      LetExpr _ _        -> True+      WhereExpr _ _      -> True+      RecordCreate _ _   -> True+      RecordUpdate _ _   -> True+      ArrayRange _ _     -> True+      TypeAnnotation _ _ -> True+      _                  -> False++showNestedInfixFnBody :: FnBody -> String+showNestedInfixFnBody x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      InfixFnApply _ _   -> True+      LeftOpSection _ _  -> True+      RightOpSection _ _ -> True+      LambdaExpr _ _     -> True+      LetExpr _ _        -> True+      WhereExpr _ _      -> True+      RecordCreate _ _   -> True+      RecordUpdate _ _   -> True+      ArrayRange _ _     -> True+      TypeAnnotation _ _ -> True+      _                  -> False
+ src/SyntaxTrees/Purescript/ModuleDef.hs view
@@ -0,0 +1,121 @@+module SyntaxTrees.Purescript.ModuleDef where++import Data.Monoid.HT                  (when)+import SyntaxTrees.Purescript.ClassDef (ClassDef, DerivingDef, InstanceDef)+import SyntaxTrees.Purescript.Common   (Class, Module, Var, VarOp)+import SyntaxTrees.Purescript.DataDef  (DataDef, NewTypeDef, TypeDef)+import SyntaxTrees.Purescript.FnDef    (FnDefOrSig (Sig), InfixFnDef)+import SyntaxTrees.Purescript.Type     (TypeVar)+import Utils.String                    (joinMaybe, joinWords, wrapParens,+                                        wrapParensCsv, (+++))+++data ModuleDef+  = ModuleDef+      { name    :: Module+      , export  :: Maybe ModuleExport+      , imports :: [ModuleImport]+      , defs    :: [InternalDef]+      }++newtype ModuleExport+  = ModuleExport [ModuleExportDef]++data ModuleExportDef+  = ModuleExportDef ImportExportDef+  | FullModuleExport Module++data ModuleImport+  = ModuleImport+      { module'   :: Module+      , hiding    :: Bool+      , imporDefs :: [ModuleImportDef]+      , alias     :: Maybe Module+      }++data ModuleImportDef+  = ModuleImportDef ImportExportDef++data ImportExportDef+  = Member ModuleMember+  | FullData TypeVar+  | FilteredData TypeVar [ModuleMember]+  | FullClass Class++data ModuleMember+  = VarMember Var+  | VarOpMember VarOp+  | DataMember TypeVar++data InternalDef+  = TypeDef' TypeDef+  | NewTypeDef' NewTypeDef+  | DataDef' DataDef+  | FnDefOrSig' FnDefOrSig+  | ClassDef' ClassDef+  | InstanceDef' InstanceDef+  | DerivingDef' DerivingDef+  | InfixFnDef' InfixFnDef+++++instance Show ModuleDef where+  show (ModuleDef x y z t) =+    joinWords ["module",+               show x,+               foldMap show y,+               "where",+               "\n\n" ++ unlines (show <$> z),+               "\n\n" ++ foldMap (\def ->+                  internalDefPrefixSeparator def +++                  show def +++                  internalDefPostfixSeparator def) t]++instance Show ModuleExport where+  show (ModuleExport x) = wrapParensCsv x++instance Show ModuleExportDef where+  show (ModuleExportDef x)  = show x+  show (FullModuleExport x) = "module" +++ show x++instance Show ModuleImport where+  show (ModuleImport x y z t) =+    joinWords ["import",+               show x,+               when y "hiding",+               wrapParensCsv z,+               "as" `joinMaybe` t]++instance Show ModuleImportDef where+  show (ModuleImportDef x) = show x++instance Show ImportExportDef where+  show (Member x)         = show x+  show (FullData x)       = show x ++ wrapParens ".."+  show (FilteredData x y) = show x ++ wrapParensCsv y+  show (FullClass x)      = "class" +++ show x++instance Show ModuleMember where+  show (VarMember x)   = show x+  show (VarOpMember x) = wrapParens $ show x+  show (DataMember x)  = show x++instance Show InternalDef where+  show (TypeDef' x)     = show x+  show (NewTypeDef' x)  = show x+  show (DataDef' x)     = show x+  show (FnDefOrSig' x)  = show x+  show (ClassDef' x)    = show x+  show (InstanceDef' x) = show x+  show (DerivingDef' x) = show x+  show (InfixFnDef' x)  = show x+++internalDefPrefixSeparator :: InternalDef -> String+internalDefPrefixSeparator (DerivingDef' _) = mempty+internalDefPrefixSeparator _                = "\n"++internalDefPostfixSeparator :: InternalDef -> String+internalDefPostfixSeparator (FnDefOrSig' (Sig _)) = mempty+internalDefPostfixSeparator _                     =  "\n"
+ src/SyntaxTrees/Purescript/Pattern.hs view
@@ -0,0 +1,65 @@+module SyntaxTrees.Purescript.Pattern where++import Data.List                     (intercalate)+import SyntaxTrees.Purescript.Common (Literal, QCtor, QCtorOp, Var)+import Utils.String                  (Wrapper (Wrapper), joinMaybe,+                                      wrapCurlyCsv, wrapParens, wrapParensCsv,+                                      wrapSpaces, wrapSquareCsv, (+++))+++data Pattern+  = CtorPattern+      { ctor   :: QCtor+      , fields :: [Pattern]+      }+  | InfixCtorPattern+      { ctorOp :: QCtorOp+      , fields :: [Pattern]+      }+  | RecordPattern+      { ctor        :: QCtor+      , namedFields :: [(Var, Maybe Pattern)]+      }+  | AliasedPattern Var Pattern+  | ArrayPattern [Pattern]+  | TuplePattern [Pattern]+  | VarPattern Var+  | LitPattern Literal+  | Wildcard++++instance Show Pattern where+  show (CtorPattern x y)      = show x +++ intercalate " " (showPatternNested <$> y)+  show (InfixCtorPattern x y) = intercalate (wrapSpaces $ show x) (showInfixPatternNested <$> y)+  show (RecordPattern x y)    = show x ++++    (wrapCurlyCsv $ Wrapper . showRecordFieldPattern <$> y)+  show (AliasedPattern x y)   = show x +++ "@" +++ showPatternNested y+  show (ArrayPattern x)       = wrapSquareCsv x+  show (TuplePattern [x])     = show x+  show (TuplePattern x)       = wrapParensCsv x+  show (VarPattern x)         = show x+  show (LitPattern x)         = show x+  show Wildcard               = "_"+++showRecordFieldPattern :: (Var, Maybe Pattern) -> String+showRecordFieldPattern (x, y) = show x ++ joinMaybe " =" y++showInfixPatternNested :: Pattern -> String+showInfixPatternNested x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      (InfixCtorPattern _ _) -> True+      _                      -> False++showPatternNested :: Pattern -> String+showPatternNested x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      (CtorPattern _ _)      -> True+      (InfixCtorPattern _ _) -> True+      (AliasedPattern _ _)   -> True+      _                      -> False
+ src/SyntaxTrees/Purescript/Type.hs view
@@ -0,0 +1,128 @@+module SyntaxTrees.Purescript.Type where++import Data.List                     (intercalate)+import SyntaxTrees.Purescript.Common (Module, QClass, showQualified)+import Utils.String                  (str, wrapParens, wrapParensCsv,+                                      wrapSpaces, (+++))+++newtype TypeParam+  = TypeParam String+  deriving (Eq, Ord)++newtype TypeVar+  = TypeVar String++data TypeCtor+  = TypeCtor String+  | Arrow+  | TupleType++data AnyKindedType+  = TypeValue Type+  | TypeFn QTypeCtor++data ClassConstraint+  = ClassConstraint QClass [Type]++data Type+  = CtorTypeApply QTypeCtor [Type]+  | ParamTypeApply TypeParam [Type]+  | NestedTypeApply Type [Type]+  | TypeVar' QTypeVar+  | TypeParam' TypeParam+  | TypeScope [TypeParam] Type+  | ClassScope [ClassConstraint] Type+++data QTypeVar+  = QTypeVar (Maybe Module) TypeVar++data QTypeCtor+  = QTypeCtor (Maybe Module) TypeCtor++++instance Show TypeParam where+  show (TypeParam x) = x++instance Show TypeVar where+  show (TypeVar x) = x++instance Show TypeCtor where+  show (TypeCtor x) = x+  show Arrow        = "->"+  show TupleType    = "()"++instance Show AnyKindedType where+  show (TypeValue x) = show x+  show (TypeFn x)    = show x++instance Show Type where+  show (CtorTypeApply (QTypeCtor _ Arrow) x)        = intercalate (wrapSpaces "->")+    (showArrowTypeNested <$> x)+  show (CtorTypeApply x@(QTypeCtor _ (TypeCtor _)) y) = show x ++++    (intercalate " " $ showTypeNested <$> y)+  show (CtorTypeApply (QTypeCtor _ TupleType) x)    = str (wrapSpaces "/\\") x+  show (ParamTypeApply x y) = show x  +++ (intercalate " " $ showTypeNested <$> y)+  show (NestedTypeApply x y) = show x +++ (intercalate " " $ showTypeNested <$> y)+  show (TypeVar' x) = show x+  show (TypeParam' x) = show x+  show (TypeScope x y) = "forall" +++ str " " x ++ "." +++ showTypeScopeNested y+  show (ClassScope x y) = str (wrapSpaces ",") x +++ "=>" +++ showClassScopeNested y++instance Show ClassConstraint where+  show (ClassConstraint x [y]) = show x +++ show y+  show (ClassConstraint x y)   = show x +++ wrapParensCsv y++instance Show QTypeVar where+  show (QTypeVar x y) = showQualified x y++instance Show QTypeCtor where+  show (QTypeCtor x y) = showQualified x y+++showAnyKindedTypeNested :: AnyKindedType -> String+showAnyKindedTypeNested (TypeValue x) = showTypeNested x+showAnyKindedTypeNested (TypeFn x)    = show x++showTypeNested :: Type -> String+showTypeNested x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      CtorTypeApply (QTypeCtor _ (TypeCtor _)) _ -> True+      CtorTypeApply (QTypeCtor _ Arrow) _        -> True+      CtorTypeApply (QTypeCtor _ TupleType) _    -> True+      ParamTypeApply _ _                         -> True+      NestedTypeApply _ _                        -> True+      TypeScope _ _                              -> True+      ClassScope _ _                             -> True+      _                                          -> False++showArrowTypeNested :: Type -> String+showArrowTypeNested x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      CtorTypeApply (QTypeCtor _ Arrow) _ -> True+      TypeScope _ _                       -> True+      ClassScope _ _                      -> True+      _                                   -> False++showTypeScopeNested :: Type -> String+showTypeScopeNested x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      TypeScope _ _ -> True+      _             -> False++showClassScopeNested :: Type -> String+showClassScopeNested x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      TypeScope _ _  -> True+      ClassScope _ _ -> True+      _              -> False
+ src/SyntaxTrees/Scala/Common.hs view
@@ -0,0 +1,120 @@+module SyntaxTrees.Scala.Common where++import Data.List (intercalate)+++newtype Var+  = Var String++newtype Ctor+  = Ctor String+++newtype VarOp+  = VarOp String++newtype CtorOp+  = CtorOp String++newtype TypeClass+  = TypeClass String++newtype Package+  = Package [String]+++data Literal+  = UnitLit+  | BoolLit Bool+  | IntLit String+  | FloatLit String+  | CharLit Char+  | StringLit String++data Modifier+  = Implicit+  | Lazy+  | Abstract+  | Private+  | Public+  | Protected+  | Override+  | Sealed+  | Open+++data QVar+  = QVar (Maybe Package) Var++data QCtor+  = QCtor (Maybe Package) Ctor++data QVarOp+  = QVarOp (Maybe Package) VarOp++data QCtorOp+  = QCtorOp (Maybe Package) CtorOp++data QTypeClass+  = QTypeClass (Maybe Package) TypeClass+++instance Show Var where+  show (Var x) = x++instance Show Ctor where+  show (Ctor x) = x++instance Show VarOp where+  show (VarOp x) = x++instance Show CtorOp where+  show (CtorOp x) = x++instance Show TypeClass where+  show (TypeClass x) = x+++instance Show Package where+  show (Package x) = intercalate "." x++instance Show Literal where+  show UnitLit         = "()"+  show (BoolLit True)  = "true"+  show (BoolLit False) = "false"+  show (IntLit x)      = x+  show (FloatLit x)    = x+  show (CharLit x)     = show x+  show (StringLit x)   = show x+++instance Show Modifier where+  show Implicit  = "implicit"+  show Lazy      = "lazy"+  show Abstract  = "abstract"+  show Private   = "private"+  show Public    = "public"+  show Protected = "protected"+  show Override  = "override"+  show Sealed    = "sealed"+  show Open      = "open"+++instance Show QVar where+  show (QVar x y) = showQualified x y++instance Show QCtor where+  show (QCtor x y) = showQualified x y++instance Show QVarOp where+  show (QVarOp x y) = showQualified x y++instance Show QCtorOp where+  show (QCtorOp x y) = showQualified x y++instance Show QTypeClass where+  show (QTypeClass x y) = showQualified x y+++showQualified :: (Show a, Show b) => Maybe a -> b -> String+showQualified x y = foldMap ((++ ".") . show) x ++ show y
+ src/SyntaxTrees/Scala/DataDef.hs view
@@ -0,0 +1,202 @@+module SyntaxTrees.Scala.DataDef where++import Data.Monoid.HT           (when)+import SyntaxTrees.Scala.Common (Ctor, Modifier, TypeClass)+import SyntaxTrees.Scala.FnDef  (InternalFnDef, MethodDef)+import SyntaxTrees.Scala.Type   (ArgList (..), Type, TypeCtor, TypeParam,+                                 UsingArgList)+import Utils.Foldable           (hasSome)+import Utils.String             (Empty (Empty), joinList, joinWords, str,+                                 wrapSpacedBlock, wrapSquareCsv)+++data TypeDef+  = TypeDef+      { alias      :: TypeCtor+      , typeParams :: [TypeParam]+      , type'      :: Type+      }++data OpaqueTypeDef+  = OpaqueTypeDef+      { alias      :: TypeCtor+      , typeParams :: [TypeParam]+      , type'      :: Type+      , derives    :: [TypeClass]+      }++data TraitDef+  = TraitDef+      { modifiers     :: [Modifier]+      , name          :: TypeCtor+      , typeParams    :: [TypeParam]+      , argLists      :: [ArgList]+      , usingArgLists :: [UsingArgList]+      , extends       :: [Type]+      , internalDefs  :: [InternalDef]+      }++data ClassDef+  = ClassDef+      { modifiers     :: [Modifier]+      , name          :: TypeCtor+      , typeParams    :: [TypeParam]+      , argLists      :: [ArgList]+      , usingArgLists :: [UsingArgList]+      , extends       :: [Type]+      , internalDefs  :: [InternalDef]+      }++data ObjectDef+  = ObjectDef+      { modifiers    :: [Modifier]+      , name         :: TypeCtor+      , extends      :: [Type]+      , internalDefs :: [InternalDef]+      }+++data EnumDef+  = EnumDef+      { modifiers     :: [Modifier]+      , name          :: TypeCtor+      , typeParams    :: [TypeParam]+      , argLists      :: [ArgList]+      , usingArgLists :: [UsingArgList]+      , derives       :: [TypeClass]+      , cases         :: [EnumCaseDef]+      }++data EnumCaseDef+  = EnumCaseDef+      { name          :: Ctor+      , argLists      :: [ArgList]+      , usingArgLists :: [UsingArgList]+      , extends       :: [Type]+      , internalDefs  :: [InternalFnDef]+      }+++data CaseClassDef+  = CaseClassDef+      { modifiers     :: [Modifier]+      , name          :: TypeCtor+      , typeParams    :: [TypeParam]+      , argLists      :: [ArgList]+      , usingArgLists :: [UsingArgList]+      , derives       :: [TypeClass]+      , extends       :: [Type]+      , internalDefs  :: [InternalFnDef]+      }++data CaseObjectDef+  = CaseObjectDef+      { modifiers    :: [Modifier]+      , name         :: TypeCtor+      , derives      :: [TypeClass]+      , extends      :: [Type]+      , internalDefs :: [InternalFnDef]+      }++data ExtensionDef+  = ExtensionDef+      { typeParams    :: [TypeParam]+      , argLists      :: [ArgList]+      , usingArgLists :: [UsingArgList]+      , methodDefs    :: [MethodDef]+      }+++data InternalDef+  = Fn InternalFnDef+  | TypeAlias TypeDef+  | OpaqueType OpaqueTypeDef+  | Trait TraitDef+  | Class ClassDef+  | Object ObjectDef+  | Enum EnumDef+  | EnumCase EnumCaseDef+  | CaseClass CaseClassDef+  | CaseObject CaseObjectDef+  | Extension ExtensionDef+++instance Show TypeDef where+  show (TypeDef x y z) =+    joinWords ["type",+               show x,+               wrapSquareCsv y,+               "=",+               show z]++instance Show OpaqueTypeDef where+  show (OpaqueTypeDef x y z t) =+    joinWords ["opaque type",+               show x,+               wrapSquareCsv y,+               "=",+               show z,+               joinList "derives" "," t]++instance Show TraitDef where+  show (TraitDef x y z t u v w) =+    showStructure "trait" x y z t u [] v w++instance Show ClassDef where+  show (ClassDef x y z t u v w) =+    showStructure "class" x y z t u [] v w++instance Show ObjectDef where+  show (ObjectDef x y z t) =+    showStructure "object" x y [] [] [] [] z t++instance Show EnumDef where+  show (EnumDef x y z t u v w) =+    showStructure "enum" x y z t u v [] w++instance Show EnumCaseDef where+  show (EnumCaseDef x y z t u) =+    showStructure "case" [] x [] y z [] t u++instance Show CaseClassDef where+  show (CaseClassDef x y z t u v w r) =+    showStructure "case class" x y z t u v w r++instance Show CaseObjectDef where+  show (CaseObjectDef x y z t u) =+    showStructure "case object" x y [] [] [] z t u++instance Show ExtensionDef where+  show (ExtensionDef x y z t) =+    showStructure "extension" [] Empty x y z [] [] t++++showStructure :: (Show a, Show b) => String -> [Modifier] -> a -> [TypeParam]+                 -> [ArgList] -> [UsingArgList] -> [TypeClass] -> [Type] -> [b]+                 -> String+showStructure  x y z t u v w r s =+  joinWords [x,+             str " " y,+             show z,+             wrapSquareCsv t,+             str " " u,+             str " " v,+             joinList "derives" ", " w,+             joinList "extends" ", " r,+             sep ++ wrapSpacedBlock s]+  where+    sep = when (x /= "extension" && hasSome s) ": "++instance Show InternalDef where+  show (Fn x)         = show x+  show (TypeAlias x)  = show x+  show (OpaqueType x) = show x+  show (Trait x)      = show x+  show (Class x)      = show x+  show (Object x)     = show x+  show (Enum x)       = show x+  show (EnumCase x)   = show x+  show (CaseClass x)  = show x+  show (CaseObject x) = show x+  show (Extension x)  = show x
+ src/SyntaxTrees/Scala/FnDef.hs view
@@ -0,0 +1,269 @@+module SyntaxTrees.Scala.FnDef where++import Data.Foldable             (Foldable (fold))+import Data.Monoid.HT            (when)+import SyntaxTrees.Scala.Common  (Literal, Modifier, QCtor, QCtorOp, QVar,+                                  QVarOp, Var)+import SyntaxTrees.Scala.Pattern (Pattern)+import SyntaxTrees.Scala.Type    (ArgList, Type, TypeParam,+                                  UsingArgList (UsingArgList))++import Data.List (intercalate)++import Conversions.ToScala.Pattern (allVars')+import Utils.Foldable              (hasSome, wrapMaybe)+import Utils.String+++data FnSig+  = FnSig+      { typeParams :: [TypeParam]+      , argLists   :: [ArgList]+      , usingArgs  :: [UsingArgList]+      , returnType :: Maybe Type+      }++data ValDef+  = ValDef+      { qualifiers :: [Modifier]+      , names      :: [Var]+      , returnType :: Maybe Type+      , body       :: Maybe FnBody+      }++data MethodDef+  = MethodDef+      { qualifiers :: [Modifier]+      , name       :: Var+      , sig        :: Maybe FnSig+      , body       :: Maybe FnBody+      }++data GivenDef+  = GivenDef+      { qualifiers :: [Modifier]+      , name       :: Maybe Var+      , typeParams :: [TypeParam]+      , usingArgs  :: [UsingArgList]+      , returnType :: Type+      , bodyOrDefs :: Either FnBody [InternalFnDef]+      }+++data FnBody+  = FnApply+      { fn   :: FnBody+      , args :: [FnBody]+      }+  | NamedFnApply+      { fn        :: FnBody+      , namedArgs :: [(Var, FnBody)]+      }+  | InfixFnApply+      { fnOps :: [FnOp]+      , args  :: [FnBody]+      }+  | LambdaExpr+      { patterns :: [Pattern]+      , body     :: FnBody+      }+  | LetExpr+      { fnBindings :: [InternalFnDef]+      , body       :: FnBody+      }+  | IfExpr+      { cond       :: FnBody+      , ifBranch   :: FnBody+      , elseBranch :: FnBody+      }+  | CondExpr+      { whenBranches :: [WhenExpr]+      , elseBranch   :: FnBody+      }+  | ForExpr+      { steps :: [ForStep]+      , yield :: FnBody+      }+  | MatchExpr+      { matchee :: FnBody+      , cases   :: [CaseBinding]+      }+  | TopLevelMatchExpr+      { cases :: [CaseBinding]+      }+  | BodySelection FnBody [Var]+  | Tuple [FnBody]+  | FnOp' FnOp+  | FnVar' FnVar+  | Literal' Literal++data FnVar+  = Selection QVar [Var]+  | Var' QVar+  | Ctor' QCtor++data FnOp+  = VarOp' QVarOp+  | CtorOp' QCtorOp++data ForStep+  = ForBinding [Var] FnBody+  | LetBinding [InternalFnDef]+  | Condition FnBody++data CaseBinding+  = CaseBinding+      { pattern' :: Pattern+      , guard    :: Maybe FnBody+      , body     :: FnBody+      }++data InternalFnDef+  = FnVal ValDef+  | FnMethod MethodDef+  | FnGiven GivenDef++data WhenExpr+  = WhenExpr+      { cond :: FnBody+      , body :: FnBody+      }++++instance Show FnSig where+  show (FnSig x y z t) =+    ("" `joinMaybe`+     (Wrapper <$> wrapMaybe (joinWords [wrapSquareCsv x,+                                        str " " y,+                                        str " " z])))+    ++ ":" `joinMaybe` t++instance Show ValDef where+  show (ValDef x y z t) =+    joinWords [str " " x,+               "val",+               showVal y z t]++instance Show MethodDef where+  show (MethodDef x y z t) =+    joinWords [str " " x,+               "def",+               showDef y z t]++instance Show GivenDef where+  show (GivenDef x y z t u v) =+    joinWords [str " " x,+               "given",+               showGiven y z t u v]++instance Show FnBody where+  show (FnApply x y)+    | (FnVar' (Ctor' _)) <- x = joinWords [show x, wrapParensCsv y]+    | otherwise = joinWords [show x,+                             joinWords $ wrapParens . show <$> y]+  show (NamedFnApply x y) = joinWords [show x, wrapParensCsv $ Wrapper .+                                      (\(a, b) -> show a +++ "=" +++ show b) <$> y]+  show (InfixFnApply x [y]) = showForInfix y +++ foldMap show x+  show (InfixFnApply x y) = strs (wrapSpaces . show <$> x)+                                 (showForInfix <$> y)++  show (BodySelection x y) = intercalate "." (show x : (show <$> y))++  show (LambdaExpr [] y)  = wrapParens $ show y+  show (LambdaExpr [x] y)+    | allVars' [x] = wrapParens $ joinWords [show x, "=>", show y]+  show (LambdaExpr x y)+    | allVars' x = wrapParens $ joinWords [wrapParensCsv x, "=>", show y]+    | otherwise  = wrapCurly $ joinWords ["case", wrapParensCsv x,+                                          "=>", show y]+  show (LetExpr x y)      = wrapLetContext x y+  show (Tuple [x])        = show x+  show (Tuple x)          = wrapParensCsv x+  show (FnOp' x)          = wrapParens $ show x+  show (FnVar' x)         = show x+  show (Literal' x)       = show x+  show (IfExpr x y z)     = joinWords ["if", show x,+                                       "then", show y,+                                       "else", show z]+  show (CondExpr x y)     = str ("\n" +++ wrapSpaces "else")+                                (Wrapper <$> ((show <$> x) ++ [show y]))+  show (ForExpr x y)      = joinWords ["for",+                                      wrapBlock x,+                                      "yield",+                                      show y]+  show (MatchExpr x y)    = joinWords [show x,+                                      "match",+                                      wrapBlock y]+  show (TopLevelMatchExpr x) = wrapBlock x++instance Show ForStep where+  show (ForBinding x y) = joinWords [showTuple x, "<-", show y]+  show (LetBinding x)   = unlines (showBinding <$> x)+  show (Condition x)    = joinWords ["if", show x]++instance Show CaseBinding where+  show (CaseBinding x y z) = joinWords ["case", show x,+                                        "if" `joinMaybe` y,+                                        "=>", show z]+instance Show WhenExpr where+  show (WhenExpr x y) = joinWords ["if", show x,+                                  "then", show y]++instance Show FnVar where+  show (Selection x y) = intercalate "." (show x : (show <$> y))+  show (Var' x)        = show x+  show (Ctor' x)       = show x++instance Show FnOp where+  show (VarOp' x)  = show x+  show (CtorOp' x) = show x++instance Show InternalFnDef where+  show (FnVal x)    = show x+  show (FnMethod x) = show x+  show (FnGiven x)  = show x+++showBinding :: InternalFnDef -> String+showBinding (FnVal (ValDef _ y _ t))         = showVal y Nothing t+showBinding (FnMethod (MethodDef _ y _ t))   = showDef y Nothing t+showBinding (FnGiven (GivenDef _ y z t u v)) = showGiven y z t u v+++showForInfix :: FnBody -> String+showForInfix x@(InfixFnApply _ _) = wrapParens $ show x+showForInfix x                    = show x+++showVal :: [Var] -> Maybe Type -> Maybe FnBody -> String+showVal x y z = showTuple x ++  ":" `joinMaybe` y+                            +++ "=" `joinMaybe` z++showDef :: Var -> Maybe FnSig -> Maybe FnBody -> String+showDef x y z = show x ++ (fold $ show <$> y)+                       +++ "=" `joinMaybe` (Wrapper . wrapSingleBlock <$> z)+++showGiven :: Maybe Var -> [TypeParam] -> [UsingArgList]+             -> Type -> Either FnBody [InternalFnDef] -> String++showGiven x y z t u = joinWords [foldMap show x,+                                 wrapSquareCsv y,+                                 str " " z,+                                 when displaySep ":",+                                 show t]+   ++ case u of+        Left body -> joinWords ["=",+                               show body]+        Right defs -> joinWords ["with",+                                wrapSpacedBlock defs]++  where+    displaySep = hasSome x || hasSome y || hasSome (foldMap fields z)+    fields (UsingArgList h) = h+++showTuple :: Show a => [a] -> String+showTuple [x] = show x+showTuple x   = wrapParens $ str ", " x
+ src/SyntaxTrees/Scala/PackageDef.hs view
@@ -0,0 +1,60 @@+module SyntaxTrees.Scala.PackageDef where++import Data.List                 (intercalate)+import SyntaxTrees.Scala.Common  (Package, Var, VarOp)+import SyntaxTrees.Scala.DataDef (InternalDef)+import SyntaxTrees.Scala.Type    (TypeVar)+import Utils.String+++data PackageDef+  = PackageDef+      { name    :: Package+      , imports :: [PackageImport]+      , defs    :: [InternalDef]+      }++data PackageImport+  = PackageImport+      { package   :: Package+      , alias     :: Maybe Package+      , importDef :: Maybe PackageImportDef+      }++data PackageImportDef+  = FullImport+  | MembersImport [PackageMember]+  | FullObjectImport TypeVar+  | FilteredObjectImport TypeVar [PackageMember]++data PackageMember+  = VarMember Var+  | VarOpMember VarOp+  | DataMember TypeVar+++instance Show PackageDef where+  show (PackageDef x y z) =+    joinLines ["package" +++ show x,+               intercalate "\n" (show <$> y),+               joinLines (show <$> z)]++instance Show PackageImport where+  show (PackageImport x y z) =+    joinWords ["import",+               show x,+               "as" `joinMaybe` y]+    ++ "." `joinMaybe` z++instance Show PackageImportDef where+  show FullImport                   = "_"+  show (MembersImport [x])          = show x+  show (MembersImport x)            = wrapCurlyCsv x+  show (FullObjectImport x)         = show x ++ "." ++ "_"+  show (FilteredObjectImport x [y]) = show x ++ "." ++ show y+  show (FilteredObjectImport x y)   = show x ++ "." ++ wrapCurlyCsv y++instance Show PackageMember where+  show (VarMember x)   = show x+  show (VarOpMember x) = show x+  show (DataMember x)  = show x
+ src/SyntaxTrees/Scala/Pattern.hs view
@@ -0,0 +1,31 @@+module SyntaxTrees.Scala.Pattern where++import SyntaxTrees.Scala.Common (Literal, QCtor, QCtorOp, Var)+import Utils.String++data Pattern+  = CtorPattern+      { ctor   :: QCtor+      , fields :: [Pattern]+      }+  | InfixCtorPattern+      { ctorOp :: QCtorOp+      , fields :: [Pattern]+      }+  | AliasedPattern Var Pattern+  | TuplePattern [Pattern]+  | VarPattern Var+  | LitPattern Literal+  | Wildcard++++instance Show Pattern where+  show (CtorPattern x y)      = show x +++ wrapParensCsv y+  show (InfixCtorPattern x y) = str (wrapSpaces $ show x) y+  show (AliasedPattern x y)   = wrapParens $ show x +++ "@" +++ show y+  show (TuplePattern [x])     = show x+  show (TuplePattern x)       = wrapParensCsv x+  show (VarPattern x)         = show x+  show (LitPattern x)         = show x+  show Wildcard               = "_"
+ src/SyntaxTrees/Scala/Type.hs view
@@ -0,0 +1,146 @@+module SyntaxTrees.Scala.Type where++import Data.List                (intercalate)+import SyntaxTrees.Scala.Common (Modifier, Package, QTypeClass, Var,+                                 showQualified)+import Utils.Foldable           (wrapMaybe)+import Utils.String             (Wrapper (..), joinMaybe, joinWords, str,+                                 wrapParens, wrapParensCsv, wrapSpaces,+                                 wrapSquareCsv, (+++))+++newtype TypeParam+  = TypeParam String++newtype TypeVar+  = TypeVar String+++data TypeCtor+  = TypeCtor String+  | Arrow+  | TupleType++data Type+  = CtorTypeApply QTypeCtor [Type]+  | ParamTypeApply TypeParam [Type]+  | NestedTypeApply Type [Type]+  | TypeVar' QTypeVar+  | TypeParam' TypeParam+  | ExistentialType+  | TypeScope [TypeParam] Type+  | ClassScope [ClassConstraint] Type+++data ClassConstraint+  = ClassConstraint QTypeClass [Type]++newtype ArgList+  = ArgList [ArgField]++newtype UsingArgList+  = UsingArgList [UsingArgField]+++data ArgField+  = ArgField+      { modifiers :: [Modifier]+      , name      :: Var+      , type'     :: Type+      }++data UsingArgField+  = UsingArgField+      { modifiers :: [Modifier]+      , name      :: Maybe Var+      , type'     :: ClassConstraint+      }++data QTypeVar+  = QTypeVar (Maybe Package) TypeVar++data QTypeCtor+  = QTypeCtor (Maybe Package) TypeCtor++++instance Show TypeParam where+  show (TypeParam x) = x++instance Show TypeVar where+  show (TypeVar x) = x++instance Show TypeCtor where+  show (TypeCtor x) = x+  show Arrow        = "->"+  show TupleType    = "()"++instance Show Type where+  show (CtorTypeApply (QTypeCtor _ Arrow) x) = intercalate (wrapSpaces "=>") $ showTypeNested <$> x+  show (CtorTypeApply x@(QTypeCtor _ (TypeCtor _)) z) = show x ++ wrapSquareCsv z+  show (CtorTypeApply (QTypeCtor _ TupleType) x)    = wrapParensCsv x+  show (ParamTypeApply x y) = show x ++ wrapSquareCsv y+  show (NestedTypeApply x y) = showTypeNested x ++ wrapSquareCsv y+  show (TypeVar' x) = show x+  show (TypeParam' x) = show x+  show ExistentialType = "?"+  show (TypeScope x y) = wrapSquareCsv x +++ "=>" +++ showTypeScopeNested y+  show (ClassScope x y) = wrapParensCsv x +++ "?=>" +++ showClassScopeNested y+++instance Show ArgList where+  show (ArgList x) = wrapParensCsv x++instance Show UsingArgList where+  show (UsingArgList x) = wrapParens $+    "using" `joinMaybe` (Wrapper <$> wrapMaybe (str ", " x))++instance Show ArgField where+  show (ArgField x y z) =+    joinWords [str " " x,+               show y ++ ":",+               show z]++instance Show UsingArgField where+  show (UsingArgField x y z) =+    joinWords [str " " x,+               ":" `joinMaybe` y,+               show z]++instance Show ClassConstraint where+  show (ClassConstraint x y) = show x ++ wrapSquareCsv y+++instance Show QTypeVar where+  show (QTypeVar x y) = showQualified x y++instance Show QTypeCtor where+  show (QTypeCtor x y) = showQualified x y+++showTypeNested :: Type -> String+showTypeNested x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      (CtorTypeApply (QTypeCtor _ Arrow) _) -> True+      (TypeScope _ _)                       -> True+      (ClassScope _ _)                      -> True+      _                                     -> False++showTypeScopeNested :: Type -> String+showTypeScopeNested x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      (TypeScope _ _) -> True+      _               -> False++showClassScopeNested :: Type -> String+showClassScopeNested x = transformFn $ show x+  where+    transformFn = if shouldWrap then wrapParens else id+    shouldWrap = case x of+      (TypeScope _ _)  -> True+      (ClassScope _ _) -> True+      _                -> False
+ src/Utils/Foldable.hs view
@@ -0,0 +1,17 @@+module Utils.Foldable where+++hasNone :: Foldable t => t a -> Bool+hasNone = null++hasSome :: Foldable t => t a -> Bool+hasSome = not . hasNone++wrapMaybe :: Foldable t => t a -> Maybe (t a)+wrapMaybe x = if hasSome x then Just x else Nothing++orPred :: (Foldable t, Functor t) => t (p -> Bool) -> p -> Bool+orPred ps a = or $ ($ a) <$> ps++andPred :: (Foldable t, Functor t) => t (p -> Bool) -> p -> Bool+andPred ps a = and $  ($ a) <$> ps
+ src/Utils/Functor.hs view
@@ -0,0 +1,10 @@+module Utils.Functor where+++ffmap :: (Functor f1, Functor f2) => (a -> b) -> f1 (f2 a) -> f1 (f2 b)+ffmap x y = (fmap . fmap) x y+++infixl 4 <<$>>+(<<$>>) :: (Functor f1, Functor f2) => (a -> b) -> f1 (f2 a) -> f1 (f2 b)+(<<$>>) = ffmap
+ src/Utils/List.hs view
@@ -0,0 +1,55 @@+module Utils.List where++import qualified Data.List.NonEmpty as Nel++import Data.Foldable    (find)+import Data.List        (groupBy, sortBy)+import Data.Tuple.Extra (first)++++safeHead :: [a] -> Maybe a+safeHead = (Nel.head <$>) . Nel.nonEmpty++safeLast :: [a] -> Maybe a+safeLast = (Nel.last <$>) . Nel.nonEmpty++safeTail :: [a] -> Maybe [a]+safeTail = (Nel.tail <$>) . Nel.nonEmpty++safeInit :: [a] -> Maybe [a]+safeInit = (Nel.init <$>) . Nel.nonEmpty+++groupByKey :: Eq b => (a -> b) -> [a] -> [[a]]+groupByKey f x = groupBy (\a b -> f a == f b) x+++groupTuplesByKey :: Eq a => [(a, b)] -> [(a, [b])]+groupTuplesByKey x = (\a -> (fst $ head a, snd <$> a)) <$>+                        groupByKey fst x+++sortByKey :: Ord b => (a -> b) -> [a] -> [a]+sortByKey f x = sortBy (\a b -> f a `compare` f b) x+++zipWithKey :: Eq a => [(a, b)] ->  [(a, c)] -> [(b, Maybe c)]+zipWithKey x y = (\a ->  (snd a, snd <$> (find (\b -> fst a == fst b) y))) <$> x+++mergeUnion :: Eq a => [(a, b)] -> [(a, c)] -> [(Maybe b, Maybe c)]+mergeUnion x y =  a ++ b+  where+    a = (first Just) <$> zipWithKey x y+    b = (tupleReverse . (first Just)) <$> zipWithKey y x+++mix :: [a] -> [a] -> [a]+mix (x : xs) (y : ys) = x : y : mix xs ys+mix [] ys             = ys+mix xs []             = xs+++tupleReverse :: (b, a) -> (a, b)+tupleReverse (x, y) = (y, x)
+ src/Utils/Maybe.hs view
@@ -0,0 +1,5 @@+module Utils.Maybe where+++cond :: Bool -> a -> Maybe a+cond x y = if x then Just y else Nothing
+ src/Utils/String.hs view
@@ -0,0 +1,135 @@+module Utils.String where++import Data.Foldable.Extra (Foldable (fold))+import Data.List           (intercalate)+import Data.Monoid.HT      (when)+import Utils.Foldable      (hasSome, wrapMaybe)+import Utils.List          (safeLast)+++wrap :: String -> String -> String -> String+wrap beg end x = when (hasSome x) $ beg ++ x ++ end++wrapBoth :: String -> String -> String+wrapBoth x = wrap x x++wrapParens :: String -> String+wrapParens = wrap "(" ")"++wrapSquare :: String -> String+wrapSquare = wrap "[" "]"++wrapCurly :: String -> String+wrapCurly = wrap "{" "}"++wrapSpaces :: String -> String+wrapSpaces = wrapBoth " "++wrapQuotes :: String -> String+wrapQuotes = wrapBoth "'"++wrapBackQuotes :: String -> String+wrapBackQuotes = wrapBoth "`"++wrapDoubleQuotes :: String -> String+wrapDoubleQuotes = wrapBoth "\""+++wrap' :: String -> String -> String -> String+wrap' beg end x = beg ++ x ++ end++wrapBoth' :: String -> String -> String+wrapBoth' x = wrap' x x++wrapParens' :: String -> String+wrapParens' = wrap' "(" ")"++wrapCurly' :: String -> String+wrapCurly' = wrap' "{" "}"++wrapQuotes' :: String -> String+wrapQuotes' = wrapBoth' "'"++wrapDoubleQuotes' :: String -> String+wrapDoubleQuotes' = wrapBoth' "\""+++wrapCsv :: Show a => [a] -> String+wrapCsv []  = mempty+wrapCsv [x] = show x+wrapCsv x   = wrapParensCsv x++wrapParensCsv :: Show a => [a] -> String+wrapParensCsv = wrapParens . str ", "++wrapSquareCsv :: Show a => [a] -> String+wrapSquareCsv = wrapSquare . str ", "++wrapCurlyCsv :: Show a => [a] -> String+wrapCurlyCsv = wrapCurly . str ", "++wrapLetContext :: (Show a, Show b) => [a] -> b -> String+wrapLetContext x y = wrapContext $ wrapBoth "\n\n" (str "\n" x) ++ show y+++wrapBlock :: Show a => [a] -> String+wrapBlock x = wrapContext $ wrapBoth "\n" $ str "\n" x++wrapSpacedBlock :: Show a => [a] -> String+wrapSpacedBlock x = wrapContext $ wrapBoth "\n\n" $ str "\n\n" x++wrapSingleBlock :: Show a => a -> String+wrapSingleBlock x = wrapContext $ wrapBoth "\n" $ show x++wrapContext :: String -> String+wrapContext = intercalate "\n" . (indent 2 <$>) . lines+  where+    indent n x = when (hasSome x) (replicate n ' ' ++ x)++wrapNewLines :: String -> String+wrapNewLines = ("\n" ++) . (++ "\n")++++str :: Show a => String -> [a] -> String+str sep xs = intercalate sep $ show <$> xs++strs :: [String] -> [String] -> String+strs seps xs = fold elems ++ fold (safeLast xs)+  where+    elems = do (x, sep) <- zip xs seps+               pure $ x ++ sep++joinWords :: [String] -> String+joinWords x = unwords $ filter hasSome x++joinLines :: [String] -> String+joinLines x = intercalate "\n\n\n" $ filter hasSome x++joinMaybe :: Show a => String -> Maybe a -> String+joinMaybe start x = foldMap ((start +++) . show) x++joinMaybePost :: Show a => Maybe a -> String ->  String+joinMaybePost x end = foldMap ((+++ end) . show) x++joinList :: Show a => String -> String -> [a] -> String+joinList start sep x = foldMap ((start +++) . str sep) (wrapMaybe x)++joinListPost :: Show a => String -> [a] -> String -> String+joinListPost sep x end = foldMap ((+++ end) . str sep) (wrapMaybe x)+++(+++) :: String -> String -> String+(+++) x y = x ++ " " ++ y++data Wrapper+  = Wrapper String++instance Show Wrapper where+  show (Wrapper x) = x++data Empty+  = Empty++instance Show Empty where+  show Empty = mempty