summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPeterSelinger <>2018-11-08 19:48:00 (GMT)
committerhdiff <hdiff@hdiff.luite.com>2018-11-08 19:48:00 (GMT)
commit7fec4ee74390e9a1cc34b89e0544896462147258 (patch)
treebb7755776526ade803084ab0523b513fe73a54e5
version 0.1.0.00.1.0.0
-rw-r--r--ChangeLog4
-rw-r--r--LICENSE675
-rw-r--r--Nominal.hs509
-rw-r--r--Nominal/Atom.hs90
-rw-r--r--Nominal/Atomic.hs305
-rw-r--r--Nominal/Bindable.hs430
-rw-r--r--Nominal/ConcreteNames.hs90
-rw-r--r--Nominal/Generics.hs10
-rw-r--r--Nominal/Nominal.hs278
-rw-r--r--Nominal/NominalShow.hs256
-rw-r--r--Nominal/NominalSupport.hs251
-rw-r--r--Nominal/Permutation.hs146
-rw-r--r--Nominal/Unsafe.hs65
-rw-r--r--Setup.hs2
-rw-r--r--examples/CustomInstances.hs109
-rw-r--r--examples/GenericInstances.hs23
-rw-r--r--examples/Lambda.hs112
-rw-r--r--examples/Minimal.hs19
-rw-r--r--nominal.cabal82
19 files changed, 3456 insertions, 0 deletions
diff --git a/ChangeLog b/ChangeLog
new file mode 100644
index 0000000..b35a0b1
--- /dev/null
+++ b/ChangeLog
@@ -0,0 +1,4 @@
+ChangeLog
+
+v0.1.0.0 2018/11/08
+ Initial public release.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..12fc7e0
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,675 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+
diff --git a/Nominal.hs b/Nominal.hs
new file mode 100644
index 0000000..410c18b
--- /dev/null
+++ b/Nominal.hs
@@ -0,0 +1,509 @@
+-- | An efficient and easy-to-use library for defining datatypes with
+-- binders, and automatically handling bound variables and
+-- alpha-equivalence. It is based on Gabbay and Pitts's theory of
+-- nominal sets.
+--
+-- Most users should only import the top-level module "Nominal", which
+-- exports all the relevant functionality in a clean and abstract way.
+-- Its submodules, such as "Nominal.Unsafe", are implementation
+-- specific and subject to change, and should not normally be imported
+-- by user code.
+
+module Nominal (
+ -- * Overview
+ -- $OVERVIEW
+
+ -- * Atoms
+ -- $ATOMS
+ Atom,
+ AtomKind(..),
+ AtomOfKind,
+ Atomic,
+ NameSuggestion,
+
+ -- ** Creation of fresh atoms in a scope
+ -- $FRESHNESS
+ with_fresh,
+ with_fresh_named,
+ with_fresh_namelist,
+
+ -- ** Creation of fresh atoms globally
+ -- $GLOBAL_FRESHNESS
+ fresh,
+ fresh_named,
+ fresh_namelist,
+
+ -- $NOMINAL_ANCHOR
+
+ -- * Nominal types
+ -- $NOMINAL
+ Nominal(..),
+ NominalPermutation,
+ Basic(..),
+
+ -- * Binders
+ Bind,
+ (.),
+ abst,
+ open,
+ merge,
+
+ -- ** Convenience functions
+ bind,
+ bind_named,
+ bind_namelist,
+
+ -- ** The Bindable class
+ -- $BINDABLE
+ Bindable(..),
+ NominalPattern,
+
+ -- ** Non-binding patterns
+ NoBind(..),
+ nobinding,
+
+ -- * Printing of nominal values
+ -- $PRINTING
+ open_for_printing,
+ NominalSupport(..),
+ Support,
+ Literal(..),
+
+ -- $NOMINALSHOW_ANCHOR
+
+ -- * The NominalShow class
+ -- $NOMINALSHOW
+ NominalShow(..),
+ nominal_show,
+ nominal_showsPrec,
+
+ -- $DERIVING_ANCHOR
+
+ -- * Deriving generic instances
+ -- $DERIVING
+
+ -- $CUSTOM_ANCHOR
+
+ -- * Defining custom instances
+ -- $CUSTOM
+
+ -- ** Basic types
+ -- $CUSTOM_BASIC
+
+ basic_action,
+ basic_support,
+ basic_showsPrecSup,
+ basic_binding,
+
+ -- ** Recursive types
+ -- $CUSTOM_RECURSIVE
+
+ -- * Miscellaneous
+ (∘),
+ module Nominal.Generics
+)
+where
+
+import Prelude hiding ((.))
+
+import Nominal.ConcreteNames
+import Nominal.Atom
+import Nominal.Permutation
+import Nominal.Nominal
+import Nominal.NominalSupport
+import Nominal.Bindable
+import Nominal.Atomic
+import Nominal.NominalShow
+import Nominal.Generics
+
+-- ----------------------------------------------------------------------
+
+-- $OVERVIEW
+--
+-- We start with a minimal example. The following code defines a
+-- datatype of untyped lambda terms, as well as a substitution
+-- function. The important point is that the definition of lambda
+-- terms is /automatically/ up to alpha-equivalence (i.e., up to
+-- renaming of bound variables), and substitution is /automatically/
+-- capture-avoiding. These details are handled by the "Nominal"
+-- library and do not require any special programming by the user.
+--
+-- > {-# LANGUAGE DeriveGeneric #-}
+-- > {-# LANGUAGE DeriveAnyClass #-}
+-- >
+-- > import Nominal
+-- > import Prelude hiding ((.))
+-- >
+-- > -- Untyped lambda terms, up to alpha-equivalence.
+-- > data Term = Var Atom | App Term Term | Abs (Bind Atom Term)
+-- > deriving (Generic, Nominal)
+-- >
+-- > -- Capture-avoiding substitution.
+-- > subst :: Term -> Atom -> Term -> Term
+-- > subst m x (Var y)
+-- > | x == y = m
+-- > | otherwise = Var y
+-- > subst m x (App t s) = App (subst m x t) (subst m x s)
+-- > subst m x (Abs body) = open body (\y s -> Abs (y . subst m x s))
+--
+-- Let us examine this code in more detail:
+--
+-- * The first four lines are boilerplate. Any code that uses the
+-- "Nominal" library should enable the language options
+-- @DeriveGeneric@ and @DeriveAnyClass@, and should import "Nominal".
+-- We also hide the @(.)@ operator from the "Prelude", because the
+-- "Nominal" library re-purposes the period as a binding operator.
+--
+-- * The next line defines the datatype @Term@ of untyped lambda
+-- terms. Here, 'Atom' is a predefined type of atomic /names/, which
+-- we use as the names of variables. A term is either a variable, an
+-- application, or an abstraction. The type @('Bind' 'Atom' Term)@ is
+-- defined by the "Nominal" library and represents pairs (/a/,/t/) of
+-- an atom and a term, modulo alpha-equivalence. We write /a/'.'/t/ to
+-- denote such an alpha-equivalence class of pairs.
+--
+-- * The next line declares that @Term@ is a /nominal/ type, by
+-- deriving an instance of the type class 'Nominal' (and also
+-- 'Generic', which enables the magic that allows 'Nominal' instances
+-- to be derived automatically). In a nutshell, a nominal datatype is
+-- a type that is aware of the existence of atoms. The 'Bind'
+-- operation can only be applied to nominal datatypes, because
+-- otherwise alpha-equivalence would not make sense.
+--
+-- * The substitution function inputs a term /m/, a variable /x/, and
+-- a term /t/, and outputs the term obtained from /t/ by replacing all
+-- occurrences of the variable /x/ by /m/. The clauses for variables
+-- and application are straightforward. Note that atoms can be
+-- compared for equality. In the clause for abstraction, the /body/ of
+-- the abstraction, which is of type @('Bind' 'Atom' Term)@, is
+-- /opened/: this means that a /fresh/ name /y/ and a term /s/ are
+-- generated such that /body/ = /y/'.'/s/. Since the name /y/ is
+-- guaranteed to be fresh, the substitution can be recursively applied
+-- to /s/ without the possibility that /y/ may be captured in /m/ or
+-- /x/.
+
+-- ----------------------------------------------------------------------
+
+-- $ATOMS
+--
+-- /Atoms/ are things that can be bound. The important properties of
+-- atoms are: there are infinitely many of them (so we can always find
+-- a fresh one), and atoms can be compared for equality. Atoms do not
+-- have any other special properties, and in particular, they are
+-- interchangeable (any atom is as good as any other atom).
+--
+-- As shown in the introductory example above, the type 'Atom' can be
+-- used for this purpose. In addition, it is often useful to have more
+-- than one kind of atoms (for example, term variables and type
+-- variables), and/or to customize the default names that are used
+-- when atoms of each kind are displayed (for example, to use /x/,
+-- /y/, /z/ for term variables and α, β, γ for type variables).
+--
+-- The standard way to define an additional type of atoms is to define
+-- a new empty type /t/ that is an instance of 'AtomKind'. Optionally,
+-- a list of suggested names for the atoms can be provided. Then
+-- 'AtomOfKind' /t/ is a new type of atoms. For example:
+--
+-- > data VarName
+-- > instance AtomKind VarName where
+-- > suggested_names _ = ["x", "y", "z"]
+-- >
+-- > newtype Variable = AtomOfKind VarName
+--
+-- All atom types are members of the type class 'Atomic'.
+
+-- ----------------------------------------------------------------------
+
+-- $FRESHNESS
+--
+-- Sometimes we need to generate a fresh atom. In the "Nominal"
+-- library, the philosophy is that a fresh atom is usually generated
+-- for a particular /purpose/, and the use of the atom is local to
+-- that purpose. Therefore, a fresh atom should always be generated
+-- within a local /scope/. So instead of
+--
+-- > let a = fresh in something,
+--
+-- we write
+--
+-- > with_fresh (\a -> something).
+--
+-- To ensure soundness, the programmer must ensure that the fresh atom
+-- does not escape the body of the 'with_fresh' block. See the
+-- documentation of 'with_fresh' for examples of what is and is not
+-- permitted, and a more precise statement of the correctness
+-- condition.
+
+-- ----------------------------------------------------------------------
+
+-- $GLOBAL_FRESHNESS
+--
+-- Occasionally, it can be useful to generate a globally fresh atom.
+-- This is done within the 'IO' monad, and therefore, the function
+-- 'fresh' (and its friends) have no corresponding correctness
+-- condition as for 'with_fresh'.
+--
+-- These functions are primarily intended for testing. They
+-- give the user a convenient way to generate fresh names in the
+-- read-eval-print loop, for example:
+--
+-- >>> a <- fresh :: IO Atom
+-- >>> b <- fresh :: IO Atom
+-- >>> a.b.(a,b)
+-- x . y . (x,y)
+--
+-- These functions should rarely be used in programs. Normally you
+-- should use 'with_fresh' instead of 'fresh', to generate a fresh
+-- atom in a specific scope for a specific purpose. If you find
+-- yourself generating a lot of global names and not binding them,
+-- consider whether the "Nominal" library is the wrong tool for your
+-- purpose. Perhaps you should use "Data.Unique" instead?
+
+-- ----------------------------------------------------------------------
+
+-- $NOMINAL_ANCHOR #NOMINAL#
+
+-- $NOMINAL
+--
+-- Informally, a type of /nominal/ if if is aware of the existence of
+-- atoms, and knows what to do in case an atom needs to be renamed.
+-- More formally, a type is nominal if it is acted upon by the group
+-- of finitely supported permutations of atoms. Ideally, all types
+-- are nominal.
+--
+-- When using the "Nominal" library, all types whose elements can
+-- occur in the scope of a binder must be instances of the 'Nominal'
+-- type class. Fortunately, in most cases, new instances of 'Nominal'
+-- can be derived automatically.
+
+-- ----------------------------------------------------------------------
+
+-- $BINDABLE
+--
+-- The 'Bindable' class contains things that can be abstracted by
+-- binders (sometimes called /patterns/). In addition to atoms, this
+-- also includes pairs of atoms, lists of atoms, and so on.
+-- In most cases, new instances of 'Bindable' can be derived
+-- automatically.
+
+-- ----------------------------------------------------------------------
+
+-- $PRINTING
+--
+-- The printing of nominal values requires concrete names for the
+-- bound variables to be chosen in such a way that they do not clash
+-- with the names of any free variables, constants, or other bound
+-- variables. This requires the ability to compute the set of free
+-- atoms (and constants) of a term. We call this set the /support/ of
+-- a term.
+--
+-- Our mechanism for pretty-printing nominal values consists of two
+-- things: the type class 'NominalSupport', which represents terms
+-- whose support can be calculated, and the function
+-- 'open_for_printing', which handles choosing concrete names for
+-- bound variables.
+--
+-- In addition to this general-purpose mechanism, there is also the
+-- 'NominalShow' type class, which is analogous to 'Show' and provides
+-- a default representation of nominal terms.
+
+-- ----------------------------------------------------------------------
+
+-- $NOMINALSHOW_ANCHOR #NOMINALSHOW#
+
+-- $NOMINALSHOW
+--
+-- The 'NominalShow' class is analogous to Haskell's standard 'Show'
+-- class, and provides a default method for converting elements of
+-- nominal datatypes to strings. The function 'nominal_show' is
+-- analogous to 'show'. In most cases, new instances of 'NominalShow'
+-- can be derived automatically.
+
+-- ----------------------------------------------------------------------
+
+-- $DERIVING_ANCHOR #DERIVING#
+
+-- $DERIVING
+--
+-- In many cases, instances of 'Nominal', 'NominalSupport',
+-- 'NominalShow', and/or 'Bindable' can be derived automatically, using
+-- the generic \"@deriving@\" mechanism. To do so, enable the
+-- language options @DeriveGeneric@ and @DeriveAnyClass@, and derive a
+-- 'Generic' instance in addition to whatever other instances you want
+-- to derive.
+--
+-- ==== Example 1: Trees
+--
+-- > {-# LANGUAGE DeriveGeneric #-}
+-- > {-# LANGUAGE DeriveAnyClass #-}
+-- >
+-- > data MyTree a = Leaf | Branch a (MyTree a) (MyTree a)
+-- > deriving (Generic, Nominal, NominalSupport, NominalShow, Show, Bindable)
+--
+-- ==== Example 2: Untyped lambda calculus
+--
+-- Note that in the case of lambda terms, it does not make sense to
+-- derive a 'Bindable' instance, as lambda terms cannot be used as
+-- binders.
+--
+-- > {-# LANGUAGE DeriveGeneric #-}
+-- > {-# LANGUAGE DeriveAnyClass #-}
+-- >
+-- > data Term = Var Atom | App Term Term | Abs (Bind Atom Term)
+-- > deriving (Generic, Nominal, NominalSupport, NominalShow, Show)
+
+-- ----------------------------------------------------------------------
+
+-- $CUSTOM_ANCHOR #CUSTOM#
+
+-- $CUSTOM
+--
+-- There are some cases where instances of 'Nominal' and the other
+-- type classes cannot be automatically derived. These include: (a)
+-- base types such as 'Double', (b) types that are not generic, such
+-- as certain GADTs, and (c) types that require a custom 'Nominal'
+-- instance for some other reason (advanced users only!). In such
+-- cases, instances must be defined explicitly. The follow examples
+-- explain how this is done.
+
+-- ----------------------------------------------------------------------
+
+-- $CUSTOM_BASIC
+--
+-- A type is /basic/ or /non-nominal/ if its elements cannot contain
+-- atoms. Typical examples are base types such as 'Integer' and
+-- 'Bool', and other types constructed exclusively from them, such as
+-- @['Integer']@ or @'Bool' -> 'Bool'@.
+--
+-- For basic types, it is very easy to define instances of 'Nominal',
+-- 'NominalSupport', 'NominalShow', and 'Bindable': for each class
+-- method, we provide a corresponding helper function whose name
+-- starts with @basic_@ that does the correct thing. These functions
+-- can only be used to define instances for /non-nominal/ types.
+--
+-- ==== Example
+--
+-- We show how the nominal type class instances for the base type
+-- 'Double' were defined.
+--
+-- > instance Nominal Double where
+-- > (•) = basic_action
+-- >
+-- > instance NominalSupport Double where
+-- > support = basic_support
+-- >
+-- > instance NominalShow Double where
+-- > showsPrecSup = basic_showsPrecSup
+-- >
+-- > instance Bindable Double where
+-- > binding = basic_binding
+--
+-- An alternative to defining new basic type class instances is to
+-- wrap the corresponding types in the constructor 'Basic'. The type
+-- @'Basic' MyType@ is isomorphic to @MyType@, and is automatically an
+-- instance of the relevant type classes.
+
+-- ----------------------------------------------------------------------
+
+-- $CUSTOM_RECURSIVE
+--
+-- For recursive types, instances for nominal type classes can be
+-- defined by passing the relevant operations recursively down the
+-- term structure. We will use the type @MyTree@ as a running
+-- example.
+--
+-- > data MyTree a = Leaf | Branch a (MyTree a) (MyTree a)
+--
+-- ==== Nominal
+--
+-- To define an instance of 'Nominal', we must specify how
+-- permutations of atoms act on the elements of the type. For example:
+--
+-- > instance (Nominal a) => Nominal (MyTree a) where
+-- > π • Leaf = Leaf
+-- > π • (Branch a l r) = Branch (π • a) (π • l) (π • r)
+--
+-- ==== NominalSupport
+--
+-- To define an instance of 'NominalSupport', we must compute the
+-- support of each term. This can be done by applying 'support' to a
+-- tuple or list (or combination thereof) of immediate subterms. For
+-- example:
+--
+-- > instance (NominalSupport a) => NominalSupport (MyTree a) where
+-- > support Leaf = support ()
+-- > support (Branch a l r) = support (a, l, r)
+--
+-- Here is another example showing additional possibilities:
+--
+-- > instance NominalSupport Term where
+-- > support (Var x) = support x
+-- > support (App t s) = support (t, s)
+-- > support (Abs t) = support t
+-- > support (MultiApp t args) = support (t, [args])
+-- > support Unit = support ()
+--
+-- If your nominal type uses additional constants, identifiers, or
+-- reserved keywords that are not implemented as 'Atom's, but whose
+-- names you don't want to clash with the names of bound variables,
+-- declare them with 'Literal' applied to a string:
+--
+-- > support (Const str) = support (Literal str)
+--
+-- ==== NominalShow
+--
+-- Custom 'NominalShow' instances require a definition of the
+-- 'showsPrecSup' function. This is very similar to the 'showsPrec'
+-- function of the 'Show' class, except that the function takes the
+-- term's support as an additional argument. Here is how it is done
+-- for the @MyTree@ datatype:
+--
+-- > instance (NominalShow a) => NominalShow (MyTree a) where
+-- > showsPrecSup sup d Leaf = showString "Leaf"
+-- > showsPrecSup sup d (Branch a l r) =
+-- > showParen (d > 10) $
+-- > showString "Branch "
+-- > ∘ showsPrecSup sup 11 a
+-- > ∘ showString " "
+-- > ∘ showsPrecSup sup 11 l
+-- > ∘ showString " "
+-- > ∘ showsPrecSup sup 11 r
+--
+-- ==== Bindable
+--
+-- The 'Bindable' class requires a function 'binding', which maps a
+-- term to the corresponding pattern. The recursive cases use the
+-- 'Applicative' structure of the 'NominalPattern' type.
+--
+-- Here is how we could define a 'Bindable' instance for the
+-- @MyTree@ type. We use the \"applicative do\" notation for
+-- convenience, although this is not essential.
+--
+-- > {-# LANGUAGE ApplicativeDo #-}
+-- >
+-- > instance (Bindable a) => Bindable (MyTree a) where
+-- > binding Leaf = do
+-- > pure Leaf
+-- > binding (Branch a l r) = do
+-- > a' <- binding a
+-- > l' <- binding l
+-- > r' <- binding r
+-- > pure (Branch a' l' r')
+--
+-- To embed non-binding sites within a pattern, replace 'binding' by
+-- 'nobinding' in the recursive call. For further discussion of
+-- non-binding patterns, see also 'NoBind'. Here is an example:
+--
+-- > {-# LANGUAGE ApplicativeDo #-}
+-- >
+-- > data HalfBinder a b = HalfBinder a b
+-- >
+-- > instance (Bindable a) => Bindable (HalfBinder a b) where
+-- > binding (HalfBinder a b) = do
+-- > a' <- binding a
+-- > b' <- nobinding b
+-- > pure (HalfBinder a' b')
+--
+-- The effect of this is that the /a/ is bound and /b/ is not bound in
+-- the term @(HalfBinder /a/ /b/)./t/@,
+--
diff --git a/Nominal/Atom.hs b/Nominal/Atom.hs
new file mode 100644
index 0000000..9f8d9d1
--- /dev/null
+++ b/Nominal/Atom.hs
@@ -0,0 +1,90 @@
+-- | This module provides a type of atoms. An atom is a globally
+-- unique identifier that also has a concrete name, as well as
+-- additional name suggestions (in case it must be renamed).
+
+module Nominal.Atom where
+
+import Data.Unique
+
+import Nominal.Unsafe
+import Nominal.ConcreteNames
+
+-- ----------------------------------------------------------------------
+-- * Atoms
+
+-- | An atom is a globally unique, opaque value.
+data Atom =
+ -- | An atom consists of a unique identifier, a concrete name, and
+ -- some optional name suggestions.
+ Atom Unique String NameGen
+
+
+instance Eq Atom where
+ -- We only compare the unique identifier, because the name
+ -- suggestions may be large or even infinite.
+ Atom x n ng == Atom x' n' ng' = x == x'
+
+-- | User code should /not/ explicitly compare atoms for relative
+-- ordering, because this is not referentially transparent (can be
+-- unsound). However, we define an 'Ord' instance for atoms anyway,
+-- because it permits atoms to be used as keys in 'Set's and 'Map's.
+instance Ord Atom where
+ -- We only compare the unique identifier, because the name
+ -- suggestions may be large or even infinite.
+ compare (Atom x n ng) (Atom x' n' ng') = compare x x'
+
+instance Show Atom where
+ show = atom_show
+
+-- ----------------------------------------------------------------------
+-- ** Basic operations on atoms
+
+-- | Return the name of an atom.
+atom_show :: Atom -> String
+atom_show (Atom x n ng) = n
+
+-- | Return the suggested names of an atom.
+atom_names :: Atom -> NameGen
+atom_names (Atom x n ng) = ng
+
+-- ----------------------------------------------------------------------
+-- ** Creation of fresh atoms globally
+
+-- | Globally create a fresh atom with the given name and name
+-- suggestions.
+fresh_atom_named :: String -> NameGen -> IO Atom
+fresh_atom_named n ng = do
+ x <- newUnique
+ return (Atom x n ng)
+
+-- | Globally create a fresh atom with the given name suggestions.
+fresh_atom :: NameGen -> IO Atom
+fresh_atom ng = do
+ n <- global_new_io ng
+ fresh_atom_named n ng
+
+-- ----------------------------------------------------------------------
+-- ** Creation of fresh atoms in a scope
+
+-- | Create a fresh atom with the given name and name suggestions. To
+-- ensure soundness, the created atom must not escape the body of the
+-- 'Nominal.Atomic.with_fresh' block. Otherwise, referential
+-- transparency may be violated. For example,
+--
+-- > with_fresh id != with_fresh id.
+--
+-- See the documentation of 'Nominal.Atomic.with_fresh' for more
+-- information on the correctness criterion.
+with_fresh_atom_named :: String -> NameGen -> (Atom -> a) -> a
+with_fresh_atom_named n ng k =
+ with_unique (\x -> k (Atom x n ng))
+
+-- | Create a fresh atom with the given name suggestion.
+--
+-- Here, the call to 'global_new' is performed lazily (outside of the
+-- 'IO' monad), so an actual concrete name will only be computed on
+-- demand.
+with_fresh_atom :: NameGen -> (Atom -> a) -> a
+with_fresh_atom ng k =
+ with_fresh_atom_named (global_new ng) ng k
+
diff --git a/Nominal/Atomic.hs b/Nominal/Atomic.hs
new file mode 100644
index 0000000..81829aa
--- /dev/null
+++ b/Nominal/Atomic.hs
@@ -0,0 +1,305 @@
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DeriveAnyClass #-}
+
+-- | This module provides the class 'Atomic', which generalizes the
+-- type 'Atom'. The purpose of this is to allow users to define more
+-- than one type of atoms.
+
+module Nominal.Atomic where
+
+import Prelude hiding ((.))
+import GHC.Generics
+
+import Nominal.ConcreteNames
+import Nominal.Atom
+import Nominal.Nominal
+import Nominal.NominalSupport
+import Nominal.Bindable
+import Nominal.Unsafe
+
+-- ----------------------------------------------------------------------
+-- * The 'Atomic' class
+
+-- | A type class for atom types.
+--
+-- The suggested way to define a type of atoms is to define a new
+-- empty type /t/ that is an instance of 'AtomKind'. Optionally, a
+-- list of suggested names for the new atoms can be provided. (These
+-- will be used as the names of bound variables unless otherwise
+-- specified). Then 'AtomOfKind' /t/ is a new type of atoms.
+--
+-- > data VarName
+-- > instance AtomKind VarName where
+-- > suggested_names = ["x", "y", "z"]
+-- > newtype Variable = AtomOfKind VarName
+class (Nominal a, NominalSupport a, Eq a, Ord a, Show a, Bindable a) => Atomic a where
+ to_atom :: a -> Atom
+ from_atom :: Atom -> a
+
+ -- | The default variable names for the atom type.
+ names :: a -> NameGen
+
+instance Atomic Atom where
+ to_atom = id
+ from_atom = id
+ names a = default_namegen
+
+-- ----------------------------------------------------------------------
+-- ** Basic operations
+
+-- | Return the name of an atom.
+atomic_show :: (Atomic a) => a -> String
+atomic_show a = atom_show (to_atom a)
+
+-- ----------------------------------------------------------------------
+-- ** Creation of fresh atoms in a scope
+
+-- | Perform a computation in the presence of a fresh atom. For
+-- soundness, the programmer must ensure that the atom created does
+-- not escape the body of the 'with_fresh' block. Thus, the following
+-- uses are permitted:
+--
+-- > with_fresh (\a -> f a == g a)
+-- > with_fresh (\a -> a . f a b c)
+--
+-- Here is an example of what is /not/ permitted:
+--
+-- > with_fresh (\a -> a)
+--
+-- Technically, the correctness condition is that in an application
+--
+-- > with_fresh (\a -> body),
+--
+-- we must have /a/ # /body/ (see [Pitts 2002] for more details on
+-- what this means). Haskell does not enforce this restriction, but if
+-- a program violates it, referential transparency may not hold, which
+-- may, in the worst case, lead to unsound compiler optimizations and
+-- undefined behavior.
+with_fresh :: (Atomic a) => (a -> t) -> t
+with_fresh k = with_fresh_namelist [] k
+
+-- | A version of 'with_fresh' that permits a suggested name to be
+-- given to the atom. The name is only a suggestion, and will be
+-- changed, if necessary, to avoid clashes.
+--
+-- This function is subject to the same correctness condition as
+-- 'with_fresh'.
+with_fresh_named :: (Atomic a) => String -> (a -> t) -> t
+with_fresh_named n = unsafe_with (fresh_named n)
+
+-- | A version of 'with_fresh' that permits a list of suggested names
+-- to be specified. The first suitable name in the list will be used
+-- if possible.
+--
+-- This function is subject to the same correctness condition as
+-- 'with_fresh'.
+with_fresh_namelist :: (Atomic a) => NameSuggestion -> (a -> t) -> t
+with_fresh_namelist ns k =
+ with_fresh_atom ng (\a -> k (from_atom a))
+ where
+ NameGen ns1 ex = names (un k)
+ ns2 = if null ns then ns1 else ns
+ ng = NameGen ns2 ex
+ un :: (a -> t) -> a
+ un = undefined
+
+-- ----------------------------------------------------------------------
+-- ** Creation of fresh atoms globally
+
+-- | Generate a globally fresh atom of the given atomic type.
+fresh :: (Atomic a) => IO a
+fresh = fresh_namelist []
+
+-- | A version of 'fresh' that that permits a suggested name to be
+-- given to the atom. The name is only a suggestion, and will be
+-- changed, if necessary, when the atom is bound.
+fresh_named :: (Atomic a) => String -> IO a
+fresh_named n = result
+ where
+ result = do
+ a <- fresh_atom_named n ng
+ return (from_atom a)
+
+ NameGen ns ex = names (un result)
+ ng = NameGen [n] ex
+ un :: IO a -> a
+ un = undefined
+
+-- | A version of 'with_fresh' that permits a list of suggested names
+-- to be specified. The first suitable name in the list will be used
+-- if possible.
+fresh_namelist :: (Atomic a) => NameSuggestion -> IO a
+fresh_namelist ns = result
+ where
+ result = do
+ a <- fresh_atom ng
+ return (from_atom a)
+
+ NameGen ns1 ex = names (un result)
+ ns2 = if null ns then ns1 else ns
+ ng = NameGen ns2 ex
+ un :: IO a -> a
+ un = undefined
+
+-- $ Implementation note: the implementation of 'fresh_namelist'
+-- differs slightly from that of 'with_fresh_namelist'. The function
+-- 'fresh_namelist' generates a concrete name for the atom
+-- immediately, whereas 'with_fresh_namelist' only does so on demand.
+-- The idea is that most atoms generated by 'with_fresh_namelist' will
+-- be bound immediately and their concrete name never displayed.
+
+-- ----------------------------------------------------------------------
+-- ** Convenience functions for abstraction
+
+-- | A convenience function for constructing binders. We can write
+--
+-- > bind (\x -> t)
+--
+-- to denote the atom abstraction (x.t), where /x/ is a fresh atom.
+bind :: (Atomic a, Nominal t) => (a -> t) -> Bind a t
+bind f = with_fresh (\x -> x . f x)
+
+-- | A version of 'bind' that also takes a suggested name for the bound atom.
+bind_named :: (Atomic a, Nominal t) => String -> (a -> t) -> Bind a t
+bind_named n f = with_fresh_named n (\x -> x . f x)
+
+-- | A version of 'bind' that also take a list of suggested names for
+-- the bound atom.
+bind_namelist :: (Atomic a, Nominal t) => NameSuggestion -> (a -> t) -> Bind a t
+bind_namelist ns f = with_fresh_namelist ns (\x -> x . f x)
+
+-- ----------------------------------------------------------------------
+-- ** Merging
+
+-- | Convert an atomic binding to an atom binding.
+to_bindatom :: (Atomic a, Nominal t) => Bind a t -> BindAtom t
+to_bindatom body = open body $ \a t -> atom_abst (to_atom a) t
+
+-- | Convert an atom binding to an atomic binding.
+from_bindatom :: (Atomic a, Nominal t) => BindAtom t -> Bind a t
+from_bindatom body = atom_open body $ \a t -> (from_atom a . t)
+
+-- | Sometimes, it is necessary to open two abstractions, using the
+-- /same/ fresh name for both of them. An example of this is the
+-- typing rule for lambda abstraction in dependent type theory:
+--
+-- > Gamma, x:t |- e : s
+-- > ------------------------------------
+-- > Gamma |- Lam (x.e) : Pi t (x.s)
+--
+-- In the bottom-up reading of this rule, we are given the terms @Lam@
+-- /body/ and @Pi@ /t/ /body'/, and we require a fresh name /x/ and
+-- terms /e/, /s/ such that /body/ = (/x/./e/) and /body'/ =
+-- (/x/./s/). Crucially, the same atom /x/ should be used in both /e/
+-- and /s/, because we subsequently need to check that /e/ has type
+-- /s/ in some scope that is common to /e/ and /s/.
+--
+-- The 'merge' primitive permits us to deal with such situations. Its
+-- defining property is
+--
+-- > merge (x.e) (x.s) = (x.(e,s)).
+--
+-- We can therefore solve the above problem:
+--
+-- > open (merge body body') (\x (e,s) -> .....)
+--
+-- Moreover, the 'merge' primitive can be used to define other
+-- merge-like functionality. For example, it is easy to define a
+-- function
+--
+-- > merge_list :: (Atomic a, Nominal t) => [Bind a t] -> Bind a [t]
+--
+-- in terms of it.
+--
+-- Semantically, the 'merge' operation implements the isomorphism of
+-- nominal sets [A]T x [A]S = [A](T x S).
+--
+-- If /x/ and /y/ are atoms with user-suggested concrete names and
+--
+-- > (z.(t',s')) = merge (x.t) (y.s),
+--
+-- then /z/ will be preferably given the concrete name of /x/, but the
+-- concrete name of /y/ will be used if the name of /x/ would cause a
+-- clash.
+merge :: (Atomic a, Nominal t, Nominal s) => Bind a t -> Bind a s -> Bind a (t,s)
+merge at as = from_bindatom (atom_merge (to_bindatom at) (to_bindatom as))
+
+-- ----------------------------------------------------------------------
+-- * Multiple atom types
+
+-- | An atom kind is a type-level constant (typically an empty type)
+-- that is an instance of the 'AtomKind' class. An atom kind is
+-- optionally equipped with a list of suggested names for this kind of
+-- atom. For example:
+--
+-- > data VarName
+-- > instance AtomKind VarName where
+-- > suggested_names _ = ["x", "y", "z"]
+--
+-- > data TypeName
+-- > instance AtomKind TypeName where
+-- > suggested_names _ = ["a", "b", "c"]
+--
+-- It is possible to have infinitely many atom kinds, for example:
+--
+-- > data Zero
+-- > data Succ a
+-- > instance AtomKind Zero
+-- > instance AtomKind (Succ a)
+--
+-- Then Zero, Succ Zero, Succ (Succ Zero), etc., will all be atom kinds.
+class AtomKind a where
+ -- | An optional list of default names for this kind of atom.
+ suggested_names :: a -> NameSuggestion
+ suggested_names a = default_names
+
+ -- | An optional function for generating infinitely many distinct
+ -- names from a finite list of suggestions. The default behavior is
+ -- to append numerical subscripts. For example, the names @[x, y,
+ -- z]@ are by default expanded to @[x, y, z, x₁, y₁, z₁, x₂, y₂,
+ -- …]@, using Unicode for the subscripts. To use a a different
+ -- naming convention, redefine 'expand_names'.
+ --
+ -- It is not strictly necessary for all of the returned names to be
+ -- distinct; it is sufficient that there are infinitely many
+ -- distinct ones.
+ --
+ -- Example: the following generates new variable names by appending
+ -- primes instead of subscripts:
+ --
+ -- > expand_names _ xs = ys
+ -- > where ys = xs ++ map (++ "'") ys
+ expand_names :: a -> NameSuggestion -> [String]
+ expand_names a = expand_default
+
+-- | The type of atoms of a given kind. For example:
+--
+-- > type Variable = AtomOfKind VarName
+-- > type Type = AtomOfKind TypeName
+newtype AtomOfKind a = AtomOfKind Atom
+ deriving (Eq, Ord, Generic, Bindable)
+
+instance (AtomKind a) => Show (AtomOfKind a) where
+ show = atomic_show
+
+instance (AtomKind a) => Nominal (AtomOfKind a) where
+ π • (AtomOfKind a) = AtomOfKind (π • a)
+
+instance (AtomKind a) => NominalSupport (AtomOfKind a) where
+ support (AtomOfKind a) = support a
+
+instance (AtomKind a) => Atomic (AtomOfKind a) where
+ to_atom (AtomOfKind a) = a
+ from_atom a = AtomOfKind a
+ names f = atomofkind_names f
+
+-- | Return the list of default names associated with the /kind/ of
+-- the given atom (not the name(s) of the atom itself).
+atomofkind_names :: (AtomKind a) => AtomOfKind a -> NameGen
+atomofkind_names f = NameGen ns ex
+ where
+ ns = suggested_names (un f)
+ ex = expand_names (un f)
+ un :: AtomOfKind a -> a
+ un = undefined
diff --git a/Nominal/Bindable.hs b/Nominal/Bindable.hs
new file mode 100644
index 0000000..b870be4
--- /dev/null
+++ b/Nominal/Bindable.hs
@@ -0,0 +1,430 @@
+{-# LANGUAGE DefaultSignatures #-}
+{-# LANGUAGE TypeOperators #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE ApplicativeDo #-}
+
+-- | This module provides a type class 'Bindable'. It contains things
+-- (such as atoms, tuples of atoms, etc.) that can be abstracted by
+-- binders (sometimes also called /patterns/). Moreover, for each
+-- bindable type /a/ and nominal type /t/, it defines a type 'Bind'
+-- /a/ /t/ of abstractions.
+--
+-- We also provide some generic programming so that instances of
+-- 'Bindable' can be automatically derived in many cases.
+--
+-- For example, @(/x/,/y/)./t/@ binds a pair of atoms in /t/. It is
+-- roughly equivalent to @/x/./y/./t/@, except that it is of type
+-- 'Bind' ('Atom', 'Atom') /t/ instead of 'Bind' 'Atom' ('Bind' 'Atom'
+-- /t/).
+--
+-- If a binder contains repeated atoms, they are regarded as
+-- distinct. The binder is treated as if one atom occurrence was bound
+-- at a time, in some fixed but unspecified order. For example,
+-- @(/x/,/x/).(/x/,/x/)@ is equivalent to either @(/x/,/y/).(/x/,/x/)@
+-- or @(/x/,/y/).(/y/,/y/)@. Which of the two alternatives is chosen
+-- is implementation specific and user code should not rely on the
+-- order of abstractions in such cases.
+
+module Nominal.Bindable where
+
+import Prelude hiding ((.))
+import GHC.Generics
+
+import Nominal.Atom
+import Nominal.Nominal
+import Nominal.NominalSupport
+
+-- ----------------------------------------------------------------------
+-- * Binding lists of atoms
+
+-- | The type of abstractions of a list of atoms. It is equivalent to
+-- @'Bind' ['Atom'] /t/@, but has a more low-level implementation.
+data BindAtomList t =
+ BindNil t
+ | BindCons (BindAtom (BindAtomList t))
+ deriving (Generic, Nominal)
+
+-- | Abstract a list of atoms in a term.
+atomlist_abst :: [Atom] -> t -> BindAtomList t
+atomlist_abst [] t = BindNil t
+atomlist_abst (a:as) t = BindCons (atom_abst a (atomlist_abst as t))
+
+-- | Open a list abstraction.
+atomlist_open :: (Nominal t) => BindAtomList t -> ([Atom] -> t -> s) -> s
+atomlist_open (BindNil t) k = k [] t
+atomlist_open (BindCons body) k =
+ atom_open body $ \a body2 ->
+ atomlist_open body2 $ \as t ->
+ k (a:as) t
+
+-- | Open a list abstraction for printing.
+atomlist_open_for_printing :: (Nominal t) => Support -> BindAtomList t -> ([Atom] -> t -> Support -> s) -> s
+atomlist_open_for_printing sup (BindNil t) k = k [] t sup
+atomlist_open_for_printing sup (BindCons body) k =
+ atom_open_for_printing sup body $ \a body2 sup' ->
+ atomlist_open_for_printing sup' body2 $ \as t sup'' ->
+ k (a:as) t sup''
+
+-- | Merge a pair of list abstractions. If the lists are of different
+-- lengths, return 'Nothing'.
+atomlist_merge :: (Nominal t, Nominal s) => BindAtomList t -> BindAtomList s -> Maybe (BindAtomList (t,s))
+atomlist_merge (BindNil t) (BindNil s) = Just (BindNil (t,s))
+atomlist_merge (BindCons body1) (BindCons body2) =
+ atom_open (atom_merge body1 body2) $ \x (t,s) -> do
+ ts <- atomlist_merge t s
+ return (BindCons (atom_abst x ts))
+atomlist_merge _ _ = Nothing
+
+-- ----------------------------------------------------------------------
+-- * Binder combinators
+
+-- | A representation of patterns of type /a/. This is an abstract
+-- type with no exposed structure. The only way to construct a value
+-- of type 'NominalPattern' /a/ is through the 'Applicative' interface and by
+-- using the functions 'binding' and 'nobinding'.
+
+data NominalPattern a =
+ NominalPattern [Atom] ([Atom] -> (a, [Atom]))
+
+-- $ Implementation note: The behavior of a pattern is determined by two
+-- things: the list of bound atom occurrences (binding sites), and a
+-- renaming function that takes such a list of atoms and returns a
+-- term. For efficiency, the renaming function is stateful: it also
+-- returns a list of atoms not yet used.
+--
+-- The binding sites must be serialized in some deterministic order,
+-- and must be accepted in the same corresponding order by the
+-- renaming function.
+--
+-- If an atom occurs at multiple binding sites of the pattern, it must
+-- be serialized multiple times. The corresponding renaming function
+-- must accept fresh atoms and put them into the respective binding
+-- sites.
+--
+-- ==== Examples:
+--
+-- > binding x = NominalPattern [x] (\(x:zs) -> (x, zs))
+-- >
+-- > binding (x, y) = NominalPattern [x, y] (\(x:y:zs) -> ((x, y), zs))
+-- >
+-- > binding (x, NoBind y) = NominalPattern [x] (\(x:zs) -> ((x, NoBind y), zs))
+-- >
+-- > binding (x, x, y) = NominalPattern [x, x, y] (\(x:x':y:zs) -> ((x, x', y), zs))
+
+-- | Constructor for non-binding patterns. This can be used to mark
+-- non-binding subterms when defining a 'Bindable' instance. See
+-- <#CUSTOM "Defining custom instances"> for examples.
+nobinding :: a -> NominalPattern a
+nobinding a = NominalPattern [] (\xs -> (a, xs))
+
+-- | Constructor for a pattern binding a single atom.
+atom_binding :: Atom -> NominalPattern Atom
+atom_binding a = NominalPattern [a] (\(a:xs) -> (a, xs))
+
+-- | Map a function over a 'NominalPattern'.
+pattern_map :: (a -> b) -> NominalPattern a -> NominalPattern b
+pattern_map f (NominalPattern xs g) = NominalPattern xs h where
+ h xs = (f a, ys) where
+ (a, ys) = g xs
+
+-- | Combinator giving 'NominalPattern' an applicative structure. This is
+-- used for constructing tuple binders.
+pattern_app :: NominalPattern (a -> b) -> NominalPattern a -> NominalPattern b
+pattern_app (NominalPattern xs f) (NominalPattern ys g) = NominalPattern (xs ++ ys) h where
+ h zs = (a b, zs'') where
+ (a, zs') = f zs
+ (b, zs'') = g zs'
+
+instance Functor NominalPattern where
+ fmap = pattern_map
+
+instance Applicative NominalPattern where
+ pure = nobinding
+ f <*> b = pattern_app f b
+
+-- ----------------------------------------------------------------------
+-- * The Bindable class
+
+-- | 'Bind' /a/ /t/ is the type of atom abstractions, denoted [/A/]/T/
+-- in the nominal logic literature. Its elements are pairs (/a/,/t/)
+-- modulo alpha-equivalence. We also write /a/'.'/t/ for such an
+-- equivalence class of pairs. For full technical details on what this
+-- means, see Definition 4 of [Pitts 2002].
+
+data Bind a t =
+ Bind ([Atom] -> a) (BindAtomList t)
+
+-- | A type is 'Bindable' if its elements can be abstracted by
+-- binders. Such elements are also called /patterns/. Examples include
+-- atoms, tuples of atoms, list of atoms, etc.
+--
+-- In most cases, instances of 'Nominal' can be automatically
+-- derived. See <#DERIVING "Deriving generic instances"> for
+-- information on how to do so, and
+-- <#CUSTOM "Defining custom instances"> for how to write custom
+-- instances.
+class (Nominal a) => Bindable a where
+ -- | A function that maps a term to a pattern. New patterns can be
+ -- constructed using the 'Applicative' structure of 'NominalPattern'.
+ -- See <#CUSTOM "Defining custom instances"> for examples.
+ binding :: a -> NominalPattern a
+
+ default binding :: (Generic a, GBindable (Rep a)) => a -> NominalPattern a
+ binding x = gbinding (from x) to
+
+-- | Atom abstraction: /a/'.'/t/ represents the equivalence class of
+-- pairs (/a/,/t/) modulo alpha-equivalence.
+--
+-- We use the infix operator @(@'.'@)@, which is normally bound to
+-- function composition in the standard Haskell library. Thus, nominal
+-- programs should import the standard library like this:
+--
+-- > import Prelude hiding ((.))
+--
+-- Note that @(@'.'@)@ is a binder of the /object language/ (i.e.,
+-- whatever datatype you are defining), not of the /metalanguage/
+-- (i.e., Haskell). A term such as /a/'.'/t/ only makes sense if /a/
+-- is already defined to be some atom. Thus, binders are often used
+-- in a context of 'Nominal.with_fresh' or 'open', such as the following:
+--
+-- > with_fresh (\a -> a.a)
+(.) :: (Bindable a, Nominal t) => a -> t -> Bind a t
+a . t = Bind (fst ∘ f) (atomlist_abst xs t)
+ where
+ NominalPattern xs f = binding a
+infixr 5 .
+
+-- | An alternative non-infix notation for @(@'.'@)@. This can be
+-- useful when using qualified module names, because \"̈@Nominal..@\" is not
+-- valid syntax.
+abst :: (Bindable a, Nominal t) => a -> t -> Bind a t
+abst = (.)
+
+-- | Destructor for atom abstraction. In an ideal programming idiom,
+-- we would be able to define a function on atom abstractions by
+-- pattern matching like this:
+--
+-- > f (a.s) = body.
+--
+-- Haskell doesn't let us provide this syntax, but using the 'open'
+-- function, we can equivalently write:
+--
+-- > f t = open t (\a s -> body).
+--
+-- Each time an abstraction is opened, /a/ is guaranteed to be a fresh
+-- atom. To guarantee soundness (referential transparency and
+-- equivariance), the body is subject to the same restriction as
+-- 'Nominal.with_fresh', namely, /a/ must be fresh for the body (in symbols
+-- /a/ # /body/).
+open :: (Bindable a, Nominal t) => Bind a t -> (a -> t -> s) -> s
+open (Bind f body) k =
+ atomlist_open body (\ys t -> k (f ys) t)
+
+-- | A variant of 'open' which moreover chooses a name for the
+-- bound atom that does not clash with any free name in its
+-- scope. This function is mostly useful for building custom
+-- pretty-printers for nominal terms. Except in pretty-printers, it is
+-- equivalent to 'open'.
+--
+-- Usage:
+--
+-- > open_for_printing sup t (\x s sup' -> body)
+--
+-- Here, /sup/ = 'support' /t/ (this requires a 'NominalSupport'
+-- instance). For printing to be efficient (roughly O(/n/)), the
+-- support must be pre-computed in a bottom-up fashion, and then
+-- passed into each subterm in a top-down fashion (rather than
+-- re-computing it at each level, which would be O(/n/²)). For this
+-- reason, 'open_for_printing' takes the support of /t/ as an
+-- additional argument, and provides /sup'/, the support of /s/, as an
+-- additional parameter to the body.
+open_for_printing :: (Bindable a, Nominal t) => Support -> Bind a t -> (a -> t -> Support -> s) -> s
+open_for_printing sup (Bind f body) k =
+ atomlist_open_for_printing sup body (\ys t sup' -> k (f ys) t sup')
+
+-- | Open two abstractions at once. So
+--
+-- > f t = open t (\x y s -> body)
+--
+-- is equivalent to the nominal pattern matching
+--
+-- > f (x.y.s) = body
+open2 :: (Bindable a, Bindable b, Nominal t) => Bind a (Bind b t) -> (a -> b -> t -> s) -> s
+open2 term k = open term $ \a term' -> open term' $ \a' t -> k a a' t
+
+-- | Like 'open2', but open two abstractions for printing.
+open2_for_printing :: (Bindable a, Bindable b, Nominal t) => Support -> Bind a (Bind b t) -> (a -> b -> t -> Support -> s) -> s
+open2_for_printing sup term k = open_for_printing sup term $ \a term' sup' -> open_for_printing sup' term' $ \a' t sup'' -> k a a' t sup''
+
+instance (Nominal a, Nominal t, Eq a, Eq t) => Eq (Bind a t) where
+ Bind f1 body1 == Bind f2 body2 =
+ case atomlist_merge body1 body2 of
+ Nothing -> False
+ Just bodies ->
+ atomlist_open bodies $ \xs (t1, t2) ->
+ t1 == t2 && f1 xs == f2 xs
+
+instance (Bindable a, Nominal t) => Nominal (Bind a t) where
+ π • (Bind f body) = Bind (π • f) (π • body)
+
+instance (Bindable a, NominalSupport a, NominalSupport t) => NominalSupport (Bind a t) where
+ support (Bind f body) = atomlist_open body $ \xs t ->
+ support_deletes xs (support (f xs, t))
+
+-- ----------------------------------------------------------------------
+-- * Non-binding patterns
+
+-- | The type constructor 'NoBind' permits data of arbitrary types
+-- (including nominal types) to be embedded in binders without
+-- becoming bound. For example, in the term
+--
+-- > m = (a, NoBind b).(a,b),
+--
+-- the atom /a/ is bound, but the atom /b/ remains free. Thus, /m/ is
+-- alpha-equivalent to @(x, NoBind b).(x,b)@, but not to
+-- @(x, NoBind c).(x,c)@.
+--
+-- A typical use case is using contexts as binders. A /context/ is a
+-- map from atoms to some data (for example, a /typing context/ is a
+-- map from atoms to types, and an /evaluation context/ is a map from
+-- atoms to values). If we define contexts like this:
+--
+-- > type Context t = [(Atom, NoBind t)]
+--
+-- then we can use contexts as binders. Specifically, if Γ = {/x/₁
+-- ↦ /A/₁, …, /x/ₙ ↦ /A/ₙ} is a context, then (Γ . /t/) binds the
+-- context to a term /t/. This means, /x/₁,…,/x/ₙ are bound in /t/,
+-- but not any atoms that occur in /A/₁,…,/A/ₙ. Without the use of
+-- 'NoBind', any atoms occurring on /A/₁,…,/A/ₙ would have been bound
+-- as well.
+--
+-- Even though atoms under 'NoBind' are not /binding/, they can still
+-- be /bound/ by other binders. For example, the term @/x/.(/x/,
+-- 'NoBind' /x/)@ is alpha-equivalent to @/y/.(/y/, 'NoBind'
+-- /y/)@. Another way to say this is that 'NoBind' has a special
+-- behavior on the left, but not on the right of a dot.
+
+newtype NoBind t = NoBind t
+ deriving (Show, Eq, Ord, Generic, Nominal, NominalSupport)
+
+-- ----------------------------------------------------------------------
+-- * Bindable instances
+
+-- $ Most of the time, instances of 'Bindable' should be derived using
+-- @deriving (Generic, Nominal, Bindable)@, as in this example:
+--
+-- > {-# LANGUAGE DeriveGeneric #-}
+-- > {-# LANGUAGE DeriveAnyClass #-}
+-- >
+-- > data Term = Var Atom | App Term Term | Abs (Bind Atom Term)
+-- > deriving (Generic, Nominal, Bindable)
+--
+-- In the case of non-nominal types (typically base types such as
+-- 'Double'), a 'Bindable' instance can be defined using
+-- 'basic_binding':
+--
+-- > instance Bindable MyType where
+-- > binding = basic_binding
+--
+-- In this case, a binder (/x/./t/) is equivalent to an ordinary pair
+-- (/x/,/t/), since there is no bound atom that could be renamed.
+
+-- | A helper function for defining 'Bindable' instances
+-- for non-nominal types.
+basic_binding :: a -> NominalPattern a
+basic_binding = nobinding
+
+-- Base cases
+
+instance Bindable Atom where
+ binding = atom_binding
+
+instance Bindable Bool where
+ binding = basic_binding
+
+instance Bindable Integer where
+ binding = basic_binding
+
+instance Bindable Int where
+ binding = basic_binding
+
+instance Bindable Char where
+ binding = basic_binding
+
+instance Bindable Double where
+ binding = basic_binding
+
+instance Bindable Float where
+ binding = basic_binding
+
+instance Bindable (Basic t) where
+ binding = basic_binding
+
+instance Bindable Literal where
+ binding = basic_binding
+
+instance (Nominal t) => Bindable (NoBind t) where
+ binding = nobinding
+
+-- Generic instances
+
+instance (Bindable a) => Bindable [a]
+instance Bindable ()
+instance (Bindable a, Bindable b) => Bindable (a, b)
+instance (Bindable a, Bindable b, Bindable c) => Bindable (a, b, c)
+instance (Bindable a, Bindable b, Bindable c, Bindable d) => Bindable (a, b, c, d)
+instance (Bindable a, Bindable b, Bindable c, Bindable d, Bindable e) => Bindable (a, b, c, d, e)
+instance (Bindable a, Bindable b, Bindable c, Bindable d, Bindable e, Bindable f) => Bindable (a, b, c, d, e, f)
+instance (Bindable a, Bindable b, Bindable c, Bindable d, Bindable e, Bindable f, Bindable g) => Bindable (a, b, c, d, e, f, g)
+
+-- ----------------------------------------------------------------------
+-- * Generic programming for Bindable
+
+-- | A specialized combinator. Although this functionality is
+-- expressible in terms of the applicative structure, we give a custom
+-- CPS-based implementation for performance reasons. It improves the
+-- overall performance by 14% (time) and 16% (space) in a typical
+-- benchmark.
+pattern_gpair :: NominalPattern (a x) -> NominalPattern (b x) -> ((a :*: b) x -> c) -> NominalPattern c
+pattern_gpair (NominalPattern xs f) (NominalPattern ys g) k = NominalPattern (xs ++ ys) h where
+ h zs = (k (a :*: b), zs'') where
+ (a, zs') = f zs
+ (b, zs'') = g zs'
+
+-- | A version of the 'Bindable' class suitable for generic programming.
+class GBindable f where
+ gbinding :: f a -> (f a -> b) -> NominalPattern b
+
+instance GBindable V1 where
+ gbinding = undefined -- never occurs, because V1 is empty
+
+instance GBindable U1 where
+ gbinding a k = NominalPattern [] (\xs -> (k a, xs))
+
+instance (GBindable a, GBindable b) => GBindable (a :*: b) where
+ gbinding (a :*: b) k =
+ pattern_gpair (gbinding a id) (gbinding b id) k
+
+instance (GBindable a, GBindable b) => GBindable (a :+: b) where
+ gbinding (L1 a) k = gbinding a (\a -> k (L1 a))
+ gbinding (R1 a) k = gbinding a (\a -> k (R1 a))
+
+instance (GBindable a) => GBindable (M1 i c a) where
+ gbinding (M1 a) k = gbinding a (\a -> k (M1 a))
+
+instance (Bindable a) => GBindable (K1 i a) where
+ gbinding (K1 a) k = pattern_map k (K1 <$> binding a)
+
+-- ----------------------------------------------------------------------
+-- * Miscellaneous
+
+-- | Function composition.
+--
+-- Since we hide (.) from the standard library, and the fully
+-- qualified name of the "Prelude"'s dot operator, \"̈@Prelude..@\", is
+-- not legal syntax, we provide '∘' as an alternate notation for
+-- composition.
+(∘) :: (b -> c) -> (a -> b) -> (a -> c)
+(g ∘ f) x = g (f x)
diff --git a/Nominal/ConcreteNames.hs b/Nominal/ConcreteNames.hs
new file mode 100644
index 0000000..ac724aa
--- /dev/null
+++ b/Nominal/ConcreteNames.hs
@@ -0,0 +1,90 @@
+-- | This module provides a way to generate infinitely many distinct
+-- concrete variable names from a list of name suggestions.
+--
+-- Since bound atoms must sometimes be renamed, we need a way to
+-- generate suitable concrete names. This should be configurable on a
+-- per-atom basis, with a fallback default behavior for each atom
+-- type.
+--
+-- A name suggestion is a list of possible names. The first useable
+-- name from the list is chosen. If the list is finite and contains no
+-- useable names, then we will generate more names by appending
+-- numerical subscripts. A client can override this default behavior
+-- by specifying an infinite list of name suggestions.
+--
+-- An empty list of name suggestions counts as no suggestion, in which
+-- case a default will be used.
+--
+-- When merging two atoms (see 'Nominal.merge'), we concatenate their
+-- name suggestions. In particular, if one name has a user-specified
+-- suggestion and the other one does not, we always use the
+-- user-specified one.
+
+module Nominal.ConcreteNames where
+
+import Data.Char
+import Data.List
+import Data.Set (Set)
+import qualified Data.Set as Set
+
+-- | A name suggestion is a list of possible names. When an atom must
+-- be renamed, the first useable name from the list is chosen. If the
+-- list is finite and contains no useable names, then additional names
+-- will be generated by appending numerical subscripts. To override
+-- this behavior, redefine 'Nominal.expand_names' for the given
+-- 'AtomKind' instance, or specify an infinite list of names.
+type NameSuggestion = [String]
+
+-- | The names to use if nothing else was specified.
+default_names :: NameSuggestion
+default_names = ["x", "y", "z", "u", "v", "w", "r", "s", "t", "p", "q"]
+
+-- | Convert a digit to a subscript.
+to_subscript :: Char -> Char
+to_subscript '0' = '₀'
+to_subscript '1' = '₁'
+to_subscript '2' = '₂'
+to_subscript '3' = '₃'
+to_subscript '4' = '₄'
+to_subscript '5' = '₅'
+to_subscript '6' = '₆'
+to_subscript '7' = '₇'
+to_subscript '8' = '₈'
+to_subscript '9' = '₉'
+to_subscript c = c
+
+-- | Check if a character is a letter or underscore.
+isAlphaOrWild :: Char -> Bool
+isAlphaOrWild c = isAlpha c || c == '_'
+
+-- | Generate an infinite list of possible names from a (possibly
+-- finite) list of suggestions.
+expand_default :: NameSuggestion -> [String]
+expand_default xs0 = xs1 ++ xs3 ++ [ x ++ map to_subscript (show n) | n <- [1..], x <- xs3 ]
+ where
+ xs1 = [ x | x <- xs0, x /= "" ]
+ xs2 = [ y | x <- xs0, let y = takeWhile isAlphaOrWild x, y /= "" ]
+ xs3 = if xs2 == [] then default_names else xs2
+
+-- | A name generator consists of a (possibly finite) list of name
+-- suggestions and an /expander/, which is a function for generating
+-- more names.
+data NameGen = NameGen NameSuggestion (NameSuggestion -> [String])
+
+-- | The default name generator.
+default_namegen :: NameGen
+default_namegen = NameGen default_names expand_default
+
+-- | Compute a string that is not in the given set, and whose name is
+-- based on the supplied suggestions.
+rename_fresh :: Set String -> NameGen -> String
+rename_fresh as (NameGen ns expander) = n'
+ where
+ n' = head [ x | x <- expand_default (ns' ++ expander ns'), not (used x) ]
+ ns' = if null ns then default_names else ns
+ used x = x `Set.member` as
+
+-- | Merge two name suggestions. Essentially this appends them, but we
+-- try to avoid duplication. We use the left expander.
+combine_names :: NameGen -> NameGen -> NameGen
+combine_names (NameGen xs ex1) (NameGen ys ex2) = NameGen (xs ++ (ys \\ xs)) ex1
diff --git a/Nominal/Generics.hs b/Nominal/Generics.hs
new file mode 100644
index 0000000..23b34ef
--- /dev/null
+++ b/Nominal/Generics.hs
@@ -0,0 +1,10 @@
+-- | The sole purpose of this module is to allow us to re-export the
+-- 'Generic' class without having to re-export its documentation or
+-- the entire "GHC.Generics" module.
+
+module Nominal.Generics (
+ Generic
+ )
+where
+
+import GHC.Generics
diff --git a/Nominal/Nominal.hs b/Nominal/Nominal.hs
new file mode 100644
index 0000000..ae4b3a9
--- /dev/null
+++ b/Nominal/Nominal.hs
@@ -0,0 +1,278 @@
+{-# LANGUAGE DefaultSignatures #-}
+{-# LANGUAGE TypeOperators #-}
+{-# LANGUAGE FlexibleContexts #-}
+
+-- | This module provides the 'Nominal' type class. A type is
+-- 'Nominal' if the group of finitely supported permutations of atoms
+-- acts on it. We can abstract over an atom in such a type.
+--
+-- We also provide some generic programming so that instances of
+-- 'Nominal' can be automatically derived in most cases.
+
+module Nominal.Nominal where
+
+import Data.Map (Map)
+import qualified Data.Map as Map
+import Data.Set (Set)
+import qualified Data.Set as Set
+import GHC.Generics
+
+import Nominal.ConcreteNames
+import Nominal.Atom
+import Nominal.Permutation
+
+-- ----------------------------------------------------------------------
+-- * The Nominal class
+
+-- | A type is nominal if the group of finitely supported permutations
+-- of atoms acts on it.
+--
+-- In most cases, instances of 'Nominal' can be automatically
+-- derived. See <#DERIVING "Deriving generic instances"> for
+-- information on how to do so, and
+-- <#CUSTOM "Defining custom instances"> for how to write custom
+-- instances.
+class Nominal t where
+ -- | Apply a permutation of atoms to a term.
+ (•) :: NominalPermutation -> t -> t
+
+ default (•) :: (Generic t, GNominal (Rep t)) => NominalPermutation -> t -> t
+ π • x = to (gbullet π (from x))
+
+-- ----------------------------------------------------------------------
+-- * Deferred permutation
+
+-- | 'Defer' /t/ is the type /t/, but equipped with an explicit substitution.
+-- This is used to cache substitutions so that they can be optimized
+-- and applied all at once.
+data Defer t = Defer NominalPermutation t
+
+-- | Apply a deferred permutation.
+force :: (Nominal t) => Defer t -> t
+force (Defer sigma t) = sigma • t
+
+instance Nominal (Defer t) where
+ -- This is where 'Defer' pays off. Rather than using 'force',
+ -- we compile the permutations for later efficient use.
+ π • (Defer sigma t) = Defer (perm_composeR π sigma) t
+
+-- ----------------------------------------------------------------------
+-- * Atom abstraction
+
+-- | 'BindAtom' /t/ is the type of atom abstractions, denoted [a]t in
+-- the nominal logic literature. Its elements are of the form (a.v)
+-- modulo alpha-equivalence. For full technical details on what this
+-- means, see Definition 4 of [Pitts 2002].
+--
+-- Implementation note: we currently use an HOAS encoding, as this
+-- turns out to be far more efficient (both in time and memory usage)
+-- than the alternatives. An important invariant of the HOAS encoding
+-- is that the underlying function must only be applied to /fresh/
+-- atoms.
+data BindAtom t = BindAtom NameGen (Atom -> Defer t)
+
+-- | Atom abstraction: 'atom_abst' /a/ /t/ represents the equivalence
+-- class of pairs (/a/,/t/) modulo alpha-equivalence. We first define
+-- this for 'Atom' and later generalize to other 'Atomic' types.
+atom_abst :: Atom -> t -> BindAtom t
+atom_abst a t = BindAtom (atom_names a) (\x -> Defer (perm_swap a x) t)
+
+-- | Pattern matching for atom abstraction. In an ideal programming
+-- idiom, we would be able to define a function on atom abstractions
+-- like this:
+--
+-- > f (x.s) = body.
+--
+-- Haskell doesn't let us provide this syntax, but the 'open' function
+-- provides the equivalent syntax
+--
+-- > f t = open t (\x s -> body).
+--
+-- To be referentially transparent and equivariant, the body is
+-- subject to the same restriction as 'with_fresh', namely,
+-- /x/ must be fresh for the body (in symbols /x/ # /body/).
+atom_open :: (Nominal t) => BindAtom t -> (Atom -> t -> s) -> s
+atom_open (BindAtom ng f) k =
+ with_fresh_atom ng (\a -> k a (force (f a)))
+
+instance (Nominal t, Eq t) => Eq (BindAtom t) where
+ b1 == b2 = atom_open (atom_merge b1 b2) $ \a (t1,t2) -> t1 == t2
+
+instance (Nominal t) => Nominal (BindAtom t) where
+ π • (BindAtom n f) = BindAtom n (\x -> π • (f x))
+
+-- | Sometimes, it is necessary to open two abstractions, using the
+-- /same/ fresh name for both of them. An example of this is the
+-- typing rule for lambda abstraction in dependent type theory:
+--
+-- > Gamma, x:t |- e : s
+-- > ------------------------------------
+-- > Gamma |- Lam (x.e) : Pi t (x.s)
+--
+-- In the bottom-up reading of this rule, we are given the terms @Lam@
+-- /body/ and @Pi@ /t/ /body'/, and we require a fresh name /x/ and
+-- terms /e/, /s/ such that /body/ = (/x/./e/) and /body'/ =
+-- (/x/./s/). Crucially, the same atom /x/ should be used in both /e/
+-- and /s/, because we subsequently need to check that /e/ has type
+-- /s/ in some scope that is common to /e/ and /s/.
+--
+-- The 'merge' primitive permits us to deal with such situations. Its
+-- defining property is
+--
+-- > merge (x.e) (x.s) = (x.(e,s)).
+--
+-- We can therefore solve the above problem:
+--
+-- > open (merge body body') (\x (e,s) -> .....)
+--
+-- Moreover, the 'merge' primitive can be used to define other
+-- merge-like functionality. For example, it is easy to define a
+-- function
+--
+-- > merge_list :: (Atomic a, Nominal t) => [Bind a t] -> Bind a [t]
+--
+-- in terms of it.
+--
+-- Semantically, the 'merge' operation implements the isomorphism of
+-- nominal sets [A]T x [A]S = [A](T x S).
+--
+-- If /x/ and /y/ are atoms with user-suggested concrete names and
+--
+-- > (z.(t',s')) = merge (x.t) (y.s),
+--
+-- then /z/ will be preferably given the concrete name of /x/, but the
+-- concrete name of /y/ will be used if the name of /x/ would cause a
+-- clash.
+atom_merge :: (Nominal t, Nominal s) => BindAtom t -> BindAtom s -> BindAtom (t,s)
+atom_merge (BindAtom ng f) (BindAtom ng' g) = (BindAtom ng'' h) where
+ ng'' = combine_names ng ng'
+ h x = Defer perm_identity (force (f x), force (g x))
+
+-- ----------------------------------------------------------------------
+-- * Basic types
+
+-- | A /basic/ or /non-nominal/ type is a type whose elements cannot
+-- contain any atoms. Typical examples are base types, such as 'Integer'
+-- or 'Bool', and other types constructed exclusively from them,
+-- such as @['Integer']@ or @'Bool' -> 'Bool'@. On such types, the
+-- nominal structure is trivial, i.e., @π • /x/ = /x/@ for all /x/.
+--
+-- For convenience, we define 'Basic' as a wrapper around such types,
+-- which will automatically generate appropriate instances of
+-- 'Nominal', 'NominalSupport', 'NominalShow', and 'Bindable'. You can
+-- use it, for example, like this:
+--
+-- > type Term = Var Atom | Const (Basic Int) | App Term Term
+--
+-- Some common base types, including 'Bool', 'Char', 'Int',
+-- 'Integer', 'Double', and 'Float', are already instances of the
+-- relevant type classes, and do not need to be wrapped in 'Basic'.
+--
+-- The use of 'Basic' can sometimes have a performance advantage. For
+-- example, @'Basic' 'String'@ is a more efficient 'Nominal' instance
+-- than 'String'. Although they are semantically equivalent, the use
+-- of 'Basic' prevents having to traverse the string to check each
+-- character for atoms that are clearly not there.
+newtype Basic t = Basic t
+ deriving (Show, Eq, Ord)
+
+-- ----------------------------------------------------------------------
+-- * Nominal instances
+
+-- $ Most of the time, instances of 'Nominal' should be derived using
+-- @deriving (Generic, Nominal)@, as in this example:
+--
+-- > {-# LANGUAGE DeriveGeneric #-}
+-- > {-# LANGUAGE DeriveAnyClass #-}
+-- >
+-- > data Term = Var Atom | App Term Term | Abs (Bind Atom Term)
+-- > deriving (Generic, Nominal)
+--
+-- In the case of non-nominal types (typically base types such as
+-- 'Double'), a 'Nominal' instance can be defined using
+-- 'basic_action':
+--
+-- > instance Nominal MyType where
+-- > (•) = basic_action
+
+-- | A helper function for defining 'Nominal' instances
+-- for non-nominal types.
+basic_action :: NominalPermutation -> t -> t
+basic_action π t = t
+
+-- Base cases
+
+instance Nominal Atom where
+ (•) = perm_apply_atom
+
+instance Nominal Bool where
+ (•) = basic_action
+
+instance Nominal Integer where
+ (•) = basic_action
+
+instance Nominal Int where
+ (•) = basic_action
+
+instance Nominal Char where
+ (•) = basic_action
+
+instance Nominal Double where
+ (•) = basic_action
+
+instance Nominal Float where
+ (•) = basic_action
+
+instance Nominal (Basic t) where
+ (•) = basic_action
+
+-- Generic instances
+
+instance (Nominal t) => Nominal [t]
+instance Nominal ()
+instance (Nominal t, Nominal s) => Nominal (t,s)
+instance (Nominal t, Nominal s, Nominal r) => Nominal (t,s,r)
+instance (Nominal t, Nominal s, Nominal r, Nominal q) => Nominal (t,s,r,q)
+instance (Nominal t, Nominal s, Nominal r, Nominal q, Nominal p) => Nominal (t,s,r,q,p)
+instance (Nominal t, Nominal s, Nominal r, Nominal q, Nominal p, Nominal o) => Nominal (t,s,r,q,p,o)
+instance (Nominal t, Nominal s, Nominal r, Nominal q, Nominal p, Nominal o, Nominal n) => Nominal (t,s,r,q,p,o,n)
+
+-- Special instances
+
+instance (Nominal t, Nominal s) => Nominal (t -> s) where
+ π • f = \x -> π • (f (π' • x))
+ where
+ π' = perm_invert π
+
+instance (Ord k, Nominal k, Nominal v) => Nominal (Map k v) where
+ π • map = Map.fromList [ (π • k, π • v) | (k, v) <- Map.toList map ]
+
+instance (Ord k, Nominal k) => Nominal (Set k) where
+ π • set = Set.fromList [ π • k | k <- Set.toList set ]
+
+-- ----------------------------------------------------------------------
+-- * Generic programming for Nominal
+
+-- | A version of the 'Nominal' class suitable for generic programming.
+class GNominal f where
+ gbullet :: NominalPermutation -> f a -> f a
+
+instance GNominal V1 where
+ gbullet π x = undefined -- Does not occur, because V1 is an empty type.
+
+instance GNominal U1 where
+ gbullet π U1 = U1
+
+instance (GNominal a, GNominal b) => GNominal (a :*: b) where
+ gbullet π (a :*: b) = gbullet π a :*: gbullet π b
+
+instance (GNominal a, GNominal b) => GNominal (a :+: b) where
+ gbullet π (L1 x) = L1 (gbullet π x)
+ gbullet π (R1 x) = R1 (gbullet π x)
+
+instance (GNominal a) => GNominal (M1 i c a) where
+ gbullet π (M1 x) = M1 (gbullet π x)
+
+instance (Nominal a) => GNominal (K1 i a) where
+ gbullet π (K1 x) = K1 (π • x)
+
diff --git a/Nominal/NominalShow.hs b/Nominal/NominalShow.hs
new file mode 100644
index 0000000..43cc6d3
--- /dev/null
+++ b/Nominal/NominalShow.hs
@@ -0,0 +1,256 @@
+{-# LANGUAGE DefaultSignatures #-}
+{-# LANGUAGE TypeOperators #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+
+-- | This module provides the 'NominalShow' type class, which is an
+-- extension of 'Show' with support for renaming of bound variables.
+-- We also provide generic programming so that instances of
+-- 'NominalShow' can be automatically derived in most cases.
+
+module Nominal.NominalShow where
+
+import Data.List
+import Data.Map (Map)
+import qualified Data.Map as Map
+import Data.Set (Set)
+import qualified Data.Set as Set
+import GHC.Generics
+
+import Nominal.Atom
+import Nominal.Nominal
+import Nominal.NominalSupport
+import Nominal.Bindable
+import Nominal.Atomic
+
+-- ----------------------------------------------------------------------
+-- * Display of nominal values
+
+-- | 'NominalShow' is similar to 'Show', but with support for renaming
+-- of bound variables. With the exception of function types, most
+-- 'Nominal' types are also instances of 'NominalShow'.
+--
+-- In most cases, instances of 'NominalShow' can be automatically
+-- derived. See <#DERIVING "Deriving generic instances"> for
+-- information on how to do so, and
+-- <#CUSTOM "Defining custom instances"> for how to write custom
+-- instances.
+class (NominalSupport t) => NominalShow t where
+ -- | A nominal version of 'showsPrec'. This function takes as its
+ -- first argument the support of /t/. This is then passed into the
+ -- subterms, making printing O(/n/) instead of O(/n/²).
+ --
+ -- It is recommended to define a 'NominalShow' instance, rather than
+ -- a 'Show' instance, for each nominal type, and then either
+ -- automatically derive the 'Show' instance, or define it using
+ -- 'nominal_showsPrec'. For example:
+ --
+ -- > instance Show MyType where
+ -- > showsPrec = nominal_showsPrec
+ --
+ -- Please note: in defining 'showsPrecSup', neither 'show'
+ -- nor 'nominal_show' should be used for the recursive cases, or
+ -- else the benefit of fast printing will be lost.
+ showsPrecSup :: Support -> Int -> t -> ShowS
+
+ -- | The method 'nominal_showList' is provided to allow the
+ -- programmer to give a specialized way of showing lists of values,
+ -- similarly to 'showList'. The principal use of this is in the
+ -- 'NominalShow' instance of the 'Char' type, so that strings are
+ -- shown in double quotes, rather than as character lists.
+ nominal_showList :: Support -> [t] -> ShowS
+ nominal_showList sup ts = showString $
+ "["
+ ++ intercalate "," [ showsPrecSup sup 0 t "" | t <- ts ]
+ ++ "]"
+
+ default showsPrecSup :: (Generic t, GNominalShow (Rep t)) => Support -> Int -> t -> ShowS
+ showsPrecSup sup d x = gshowsPrecSup Pre sup d (from x)
+
+-- | Like 'show', but for nominal types. Normally all instances of
+-- 'NominalShow' are also instances of 'Show', so 'show' can usually
+-- be used instead of 'nominal_show'.
+nominal_show :: (NominalShow t) => t -> String
+nominal_show t = showsPrecSup (support t) 0 t ""
+
+-- | This function can be used in the definition of 'Show'
+-- instances for nominal types, like this:
+--
+-- > instance Show MyType where
+-- > showsPrec = nominal_showsPrec
+nominal_showsPrec :: (NominalShow t) => Int -> t -> ShowS
+nominal_showsPrec d t = showsPrecSup (support t) d t
+
+-- ----------------------------------------------------------------------
+-- * NominalShow instances
+
+-- $ Most of the time, instances of 'NominalShow' should be derived using
+-- @deriving (Generic, NominalSupport, NominalShow)@, as in this example:
+--
+-- > {-# LANGUAGE DeriveGeneric #-}
+-- > {-# LANGUAGE DeriveAnyClass #-}
+-- >
+-- > data Term = Var Atom | App Term Term | Abs (Bind Atom Term)
+-- > deriving (Generic, NominalSupport, NominalShow)
+--
+-- In the case of non-nominal types (typically base types such as
+-- 'Double'), a 'NominalShow' instance can be defined using
+-- 'basic_showsPrecSup':
+--
+-- > instance NominalShow MyType where
+-- > showsPrecSup = basic_showsPrecSup
+
+-- | A helper function for defining 'NominalShow' instances
+-- for non-nominal types. This requires an existing 'Show' instance.
+basic_showsPrecSup :: (Show t) => Support -> Int -> t -> ShowS
+basic_showsPrecSup sup d x = showsPrec d x
+
+-- Base cases
+
+instance NominalShow Atom where
+ showsPrecSup sup d t = showString (atomic_show t)
+
+instance NominalShow Bool where
+ showsPrecSup = basic_showsPrecSup
+
+instance NominalShow Integer where
+ showsPrecSup = basic_showsPrecSup
+
+instance NominalShow Int where
+ showsPrecSup = basic_showsPrecSup
+
+instance NominalShow Char where
+ showsPrecSup = basic_showsPrecSup
+ nominal_showList sup ts = shows ts
+
+instance NominalShow Double where
+ showsPrecSup = basic_showsPrecSup
+
+instance NominalShow Float where
+ showsPrecSup = basic_showsPrecSup
+
+instance (Show t) => NominalShow (Basic t) where
+ showsPrecSup = basic_showsPrecSup
+
+instance NominalShow Literal where
+ showsPrecSup = basic_showsPrecSup
+
+-- Generic instances
+
+instance NominalShow ()
+instance (NominalShow t, NominalShow s) => NominalShow (t,s)
+instance (NominalShow t, NominalShow s, NominalShow r) => NominalShow (t,s,r)
+instance (NominalShow t, NominalShow s, NominalShow r, NominalShow q) => NominalShow (t,s,r,q)
+instance (NominalShow t, NominalShow s, NominalShow r, NominalShow q, NominalShow p) => NominalShow (t,s,r,q,p)
+instance (NominalShow t, NominalShow s, NominalShow r, NominalShow q, NominalShow p, NominalShow o) => NominalShow (t,s,r,q,p,o)
+instance (NominalShow t, NominalShow s, NominalShow r, NominalShow q, NominalShow p, NominalShow o, NominalShow n) => NominalShow (t,s,r,q,p,o,n)
+
+-- Special instances
+
+instance (NominalShow t) => NominalShow [t] where
+ showsPrecSup sup d ts = nominal_showList sup ts
+
+instance (NominalShow t) => NominalShow (Defer t) where
+ showsPrecSup sup d t = showsPrecSup sup d (force t)
+
+instance (AtomKind a) => NominalShow (AtomOfKind a) where
+ showsPrecSup sup d t = showString (atomic_show t)
+
+instance (Bindable a, NominalShow a, NominalShow t) => NominalShow (Bind a t) where
+ showsPrecSup sup d t =
+ open_for_printing sup t $ \a s sup' ->
+ showParen (d > 5) $
+ showString (nominal_show a ++ " . " ++ showsPrecSup sup' 5 s "")
+
+instance (Ord k, NominalShow k, NominalShow v) => NominalShow (Map k v) where
+ showsPrecSup sup d m =
+ showParen (d > 10) $
+ showString "fromList " ∘ showsPrecSup sup 11 (Map.toList m)
+
+instance (Ord k, NominalShow k) => NominalShow (Set k) where
+ showsPrecSup sup d s =
+ showParen (d > 10) $
+ showString "fromList " ∘ showsPrecSup sup 11 (Set.toList s)
+
+instance (Bindable a, NominalShow a, NominalShow t) => Show (Bind a t) where
+ showsPrec = nominal_showsPrec
+
+-- ----------------------------------------------------------------------
+-- * Generic programming for NominalShow
+
+-- | This type keeps track of which separator to use for the next tuple.
+data Separator = Rec | Tup | Inf String | Pre
+
+-- | A version of the 'NominalShow' class suitable for generic
+-- programming. The implementation uses ideas from
+-- "Generics.Deriving.Show".
+class GNominalShow f where
+ gshowsPrecSup :: Separator -> Support -> Int -> f a -> ShowS
+ isNullary :: f a -> Bool
+ isNullary x = False
+
+instance GNominalShow V1 where
+ -- Does not occur, because V1 is an empty type.
+ gshowsPrecSup sep sup d t s = undefined
+
+instance GNominalShow U1 where
+ gshowsPrecSup sep sup d t s = s
+ isNullary x = True
+
+instance (GNominalShow a, GNominalShow b) => GNominalShow (a :*: b) where
+ gshowsPrecSup sep sup d (x :*: y) =
+ gshowsPrecSup sep sup prec x
+ ∘ showString separator
+ ∘ gshowsPrecSup sep sup prec y
+ where
+ (separator, prec) = case sep of
+ Rec -> (", ", d)
+ Tup -> (",", d)
+ Inf s -> (" " ++ s ++ " ", d)
+ Pre -> (" ", 11)
+
+instance (GNominalShow a, GNominalShow b) => GNominalShow (a :+: b) where
+ gshowsPrecSup sep sup d (L1 x) = gshowsPrecSup sep sup d x
+ gshowsPrecSup sep sup d (R1 x) = gshowsPrecSup sep sup d x
+
+instance (GNominalShow a) => GNominalShow (M1 D c a) where
+ gshowsPrecSup sep sup d (M1 x) = gshowsPrecSup sep sup d x
+
+instance (GNominalShow a, Constructor c) => GNominalShow (M1 C c a) where
+ gshowsPrecSup sep sup d c@(M1 x) =
+ case fixity of
+ Prefix
+ | isNullary x -> showString (prefix name)
+ | isTuple name -> showParen True $ gshowsPrecSup Tup sup 0 x
+ | conIsRecord c -> showParen (d > 10) $
+ showString (prefix name)
+ ∘ showString " "
+ ∘ showString "{"
+ ∘ gshowsPrecSup Rec sup 0 x
+ ∘ showString "}"
+ | otherwise -> showParen (d > 10) $
+ showString (prefix name)
+ ∘ showString " "
+ ∘ gshowsPrecSup Pre sup 11 x
+ Infix assoc prec -> showParen (d > prec) $
+ gshowsPrecSup (Inf name) sup (prec+1) x
+ where
+ name = conName c
+ prefix n@(':':s) = "(" ++ n ++ ")"
+ prefix n = n
+ fixity = conFixity c
+ isTuple ('(' : ',' : _) = True
+ isTuple _ = False
+
+instance (GNominalShow a, Selector c) => GNominalShow (M1 S c a) where
+ gshowsPrecSup sep sup d s@(M1 x)
+ | null name = gshowsPrecSup sep sup d x
+ | otherwise =
+ showString name
+ ∘ showString " = "
+ ∘ gshowsPrecSup sep sup d x
+ where
+ name = selName s
+
+instance (NominalShow a) => GNominalShow (K1 i a) where
+ gshowsPrecSup sep sup d (K1 x) = showsPrecSup sup d x
diff --git a/Nominal/NominalSupport.hs b/Nominal/NominalSupport.hs
new file mode 100644
index 0000000..9cd774b
--- /dev/null
+++ b/Nominal/NominalSupport.hs
@@ -0,0 +1,251 @@
+{-# LANGUAGE DefaultSignatures #-}
+{-# LANGUAGE TypeOperators #-}
+{-# LANGUAGE FlexibleContexts #-}
+
+-- | This module provides the 'NominalSupport' type class. It consists
+-- of those types for which the support can be calculated. With the
+-- exception of function types, most 'Nominal' types are also
+-- in 'NominalSupport'.
+--
+-- We also provide some generic programming so that instances of
+-- 'NominalSupport' can be automatically derived in most cases.
+
+module Nominal.NominalSupport where
+
+import Data.Map (Map)
+import qualified Data.Map as Map
+import Data.Set (Set)
+import qualified Data.Set as Set
+import GHC.Generics
+
+import Nominal.ConcreteNames
+import Nominal.Atom
+import Nominal.Nominal
+
+-- ----------------------------------------------------------------------
+-- * Literal strings
+
+-- | A wrapper around strings. This is used to denote any literal
+-- strings whose values should not clash with the names of bound
+-- variables. For example, if a term contains a constant symbol /c/,
+-- the name /c/ should not also be used as the name of a bound
+-- variable. This can be achieved by marking the string with
+-- 'Literal', like this
+--
+-- > data Term = Var Atom | Const (Literal String) | ...
+--
+-- Another way to use 'Literal' is in the definition of custom
+-- 'NominalSupport' instances. See
+-- <#CUSTOM "Defining custom instances"> for an example.
+
+newtype Literal = Literal String
+ deriving (Show)
+
+instance Nominal Literal where
+ (•) = basic_action
+
+-- ----------------------------------------------------------------------
+-- * Support
+
+-- | Something to be avoided can be an atom or a string.
+data Avoidee = A Atom | S String
+ deriving (Eq, Ord, Show)
+
+-- | This type provides an internal representation for the support of
+-- a nominal term, i.e., the set of atoms (and constants) occurring in
+-- it. This is an abstract type with no exposed structure. The only way
+-- to construct a value of type 'Support' is to use the function
+-- 'support'.
+newtype Support = Support (Set Avoidee)
+
+-- | The empty support.
+support_empty :: Support
+support_empty = Support Set.empty
+
+-- | The union of a list of supports.
+support_unions :: [Support] -> Support
+support_unions xs = Support (Set.unions [ x | Support x <- xs ])
+
+-- | The union of two supports.
+support_union :: Support -> Support -> Support
+support_union (Support x) (Support y) = Support (Set.union x y)
+
+-- | Add an atom to the support.
+support_insert :: Atom -> Support -> Support
+support_insert a (Support x) = Support (Set.insert (A a) x)
+
+-- | A singleton support.
+support_atom :: Atom -> Support
+support_atom a = Support (Set.singleton (A a))
+
+-- | Delete an atom from the support.
+support_delete :: Atom -> Support -> Support
+support_delete a (Support s) = Support (Set.delete (A a) s)
+
+-- | Delete a list of atoms from the support.
+support_deletes :: [Atom] -> Support -> Support
+support_deletes [] s = s
+support_deletes (a:as) s = support_deletes as (support_delete a s)
+
+-- | Add a literal string to the support.
+support_string :: String -> Support
+support_string s = Support (Set.singleton (S s))
+
+-- | Convert the support to a list of strings.
+strings_of_support :: Support -> Set String
+strings_of_support (Support s) = Set.map name s where
+ name (A a) = show a
+ name (S s) = s
+
+-- ----------------------------------------------------------------------
+-- * The NominalSupport class
+
+-- | 'NominalSupport' is a subclass of 'Nominal' consisting of those
+-- types for which the support can be calculated. With the notable
+-- exception of function types, most 'Nominal' types are also
+-- instances of 'NominalSupport'.
+--
+-- In most cases, instances of 'NominalSupport' can be automatically
+-- derived. See <#DERIVING "Deriving generic instances"> for
+-- information on how to do so, and
+-- <#CUSTOM "Defining custom instances"> for how to write custom
+-- instances.
+class (Nominal t) => NominalSupport t where
+ -- | Compute a set of atoms and strings that should not be used as
+ -- the names of bound variables.
+ support :: t -> Support
+
+ default support :: (Generic t, GNominalSupport (Rep t)) => t -> Support
+ support x = gsupport (from x)
+
+-- ----------------------------------------------------------------------
+-- * Open for printing
+
+-- | A variant of 'open' which moreover chooses a name for the bound
+-- atom that does not clash with any free name in its scope. This
+-- function is mostly useful for building custom pretty-printers for
+-- nominal terms. Except in pretty-printers, it is equivalent to
+-- 'open'.
+--
+-- Usage:
+--
+-- > open_for_printing sup t (\x s sup' -> body)
+--
+-- Here, /sup/ = 'support' /t/. For printing to be efficient (roughly
+-- O(/n/)), the support must be pre-computed in a bottom-up fashion,
+-- and then passed into each subterm in a top-down fashion (rather
+-- than re-computing it at each level, which would be O(/n/²)). For
+-- this reason, 'open_for_printing' takes the support of /t/ as an
+-- additional argument, and provides /sup'/, the support of /s/, as an
+-- additional parameter to the body.
+atom_open_for_printing :: (Nominal t) => Support -> BindAtom t -> (Atom -> t -> Support -> s) -> s
+atom_open_for_printing sup t@(BindAtom ng f) k =
+ with_fresh_atom_named n ng (\a -> k a (force (f a)) (sup' a))
+ where
+ n = rename_fresh (strings_of_support sup) ng
+ sup' a = support_insert a sup
+
+-- ----------------------------------------------------------------------
+-- * NominalSupport instances
+
+-- $ Most of the time, instances of 'NominalSupport' should be derived using
+-- @deriving (Generic, NominalSupport)@, as in this example:
+--
+-- > {-# LANGUAGE DeriveGeneric #-}
+-- > {-# LANGUAGE DeriveAnyClass #-}
+-- >
+-- > data Term = Var Atom | App Term Term | Abs (Bind Atom Term)
+-- > deriving (Generic, NominalSupport)
+--
+-- In the case of non-nominal types (typically base types such as
+-- 'Double'), a 'NominalSupport' instance can be defined using
+-- 'basic_support':
+--
+-- > instance NominalSupport MyType where
+-- > support = basic_support
+
+-- | A helper function for defining 'NominalSupport' instances
+-- for non-nominal types.
+basic_support :: t -> Support
+basic_support t = support ()
+
+-- Base cases
+
+instance NominalSupport Atom where
+ support = support_atom
+
+instance NominalSupport Bool where
+ support = basic_support
+
+instance NominalSupport Integer where
+ support = basic_support
+
+instance NominalSupport Int where
+ support = basic_support
+
+instance NominalSupport Char where
+ support = basic_support
+
+instance NominalSupport Double where
+ support = basic_support
+
+instance NominalSupport Float where
+ support = basic_support
+
+instance NominalSupport (Basic t) where
+ support = basic_support
+
+instance NominalSupport Literal where
+ support (Literal s) = support_string s
+
+-- Generic instances
+
+instance (NominalSupport t) => NominalSupport [t]
+instance NominalSupport ()
+instance (NominalSupport t, NominalSupport s) => NominalSupport (t,s)
+instance (NominalSupport t, NominalSupport s, NominalSupport r) => NominalSupport (t,s,r)
+instance (NominalSupport t, NominalSupport s, NominalSupport r, NominalSupport q) => NominalSupport (t,s,r,q)
+instance (NominalSupport t, NominalSupport s, NominalSupport r, NominalSupport q, NominalSupport p) => NominalSupport (t,s,r,q,p)
+instance (NominalSupport t, NominalSupport s, NominalSupport r, NominalSupport q, NominalSupport p, NominalSupport o) => NominalSupport (t,s,r,q,p,o)
+instance (NominalSupport t, NominalSupport s, NominalSupport r, NominalSupport q, NominalSupport p, NominalSupport o, NominalSupport n) => NominalSupport (t,s,r,q,p,o,n)
+
+-- Special instances
+
+instance (NominalSupport t) => NominalSupport (BindAtom t) where
+ support (BindAtom ng f) =
+ with_fresh_atom ng (\a -> support_delete a (support (f a)))
+
+instance (NominalSupport t) => NominalSupport (Defer t) where
+ support t = support (force t)
+
+instance (Ord k, NominalSupport k, NominalSupport v) => NominalSupport (Map k v) where
+ support map = support (Map.toList map)
+
+instance (Ord k, NominalSupport k) => NominalSupport (Set k) where
+ support set = support (Set.toList set)
+
+-- ----------------------------------------------------------------------
+-- * Generic programming for NominalSupport
+
+-- | A version of the 'NominalSupport' class suitable for generic programming.
+class GNominalSupport f where
+ gsupport :: f a -> Support
+
+instance GNominalSupport V1 where
+ gsupport x = undefined -- Does not occur, because V1 is an empty type.
+
+instance GNominalSupport U1 where
+ gsupport U1 = support_empty
+
+instance (GNominalSupport a, GNominalSupport b) => GNominalSupport (a :*: b) where
+ gsupport (a :*: b) = support_union (gsupport a) (gsupport b)
+
+instance (GNominalSupport a, GNominalSupport b) => GNominalSupport (a :+: b) where
+ gsupport (L1 x) = gsupport x
+ gsupport (R1 x) = gsupport x
+
+instance (GNominalSupport a) => GNominalSupport (M1 i c a) where
+ gsupport (M1 x) = gsupport x
+
+instance (NominalSupport a) => GNominalSupport (K1 i a) where
+ gsupport (K1 x) = support x
diff --git a/Nominal/Permutation.hs b/Nominal/Permutation.hs
new file mode 100644
index 0000000..6151866
--- /dev/null
+++ b/Nominal/Permutation.hs
@@ -0,0 +1,146 @@
+-- | This module provides an efficient implementation of finitely
+-- supported permutations of atoms. Compositions and inverses can
+-- both be computed with O(/n/) 'Map' lookup operations.
+
+module Nominal.Permutation where
+
+import Data.List
+import Data.Map (Map)
+import qualified Data.Map as Map
+
+import Nominal.Atom
+
+-- ----------------------------------------------------------------------
+-- * The monoid of permutations
+
+-- | The monoid of finitely supported permutations on atoms.
+newtype Perm = Perm (Map Atom Atom)
+ deriving (Eq, Show)
+
+-- | The identity permutation. O(1).
+p_identity :: Perm
+p_identity = Perm Map.empty
+
+-- | Compose two permutations. O(/m/) where /m/ is the size of the
+-- right permutation.
+p_composeR :: Perm -> Perm -> Perm
+p_composeR s@(Perm sigma) (Perm tau) = Perm rho
+ where
+ rho = Map.foldrWithKey f sigma tau
+ f a b rho = rho'
+ where
+ c = p_apply_atom s b
+ rho'
+ | a == c = Map.delete a rho
+ | otherwise = Map.insert a c rho
+
+-- | Compose two permutations. O(/n/) where /n/ is the size of the
+-- left permutation. This also requires the inverse of the right
+-- permutation as an input.
+p_composeL :: Perm -> Perm -> Perm -> Perm
+p_composeL (Perm sigma) (Perm tau) t'@(Perm tau_inv) = Perm rho
+ where
+ rho = Map.foldrWithKey f tau sigma
+ f a b rho = rho'
+ where
+ c = p_apply_atom t' a
+ rho'
+ | c == b = Map.delete c rho
+ | otherwise = Map.insert c b rho
+
+-- | Apply a permutation to an atom. O(1).
+p_apply_atom :: Perm -> Atom -> Atom
+p_apply_atom (Perm sigma) a =
+ case Map.lookup a sigma of
+ Nothing -> a
+ Just b -> b
+
+-- | Swap /a/ and /b/. O(1).
+p_swap :: Atom -> Atom -> Perm
+p_swap a b
+ | a == b = p_identity
+ | otherwise = Perm (Map.singleton a b `Map.union` Map.singleton b a)
+
+-- | Return the domain of a permutation. O(n).
+p_domain :: Perm -> [Atom]
+p_domain (Perm sigma) = Map.keys sigma
+
+-- ----------------------------------------------------------------------
+-- * The group of permutations
+
+-- | The group of finitely supported permutations on atoms. This is
+-- an abstract type with no exposed structure.
+data NominalPermutation = Permutation Perm Perm
+ -- ^ Implementation note: If we used 'Perm' directly, inverting a
+ -- permutation would be O(n). We make inverting O(1) by storing a
+ -- permutation together with its inverse. Because of laziness, the
+ -- inverse will not be computed unless it is used.
+ deriving (Eq)
+
+-- | A type synonym.
+type Permutation = NominalPermutation
+
+-- | The identity permutation. O(1).
+perm_identity :: Permutation
+perm_identity = Permutation p_identity p_identity
+
+-- | Compose two permutations. O(/m/) where /m/ is the size of the
+-- right permutation.
+perm_composeR :: Permutation -> Permutation -> Permutation
+perm_composeR (Permutation sigma sinv) (Permutation tau tinv) = Permutation rho rinv
+ where
+ rho = p_composeR sigma tau
+ rinv = p_composeL tinv sinv sigma
+
+-- | Compose two permutations. O(/n/) where /n/ is the size of the
+-- left permutation.
+perm_composeL :: Permutation -> Permutation -> Permutation
+perm_composeL (Permutation sigma sinv) (Permutation tau tinv) = Permutation rho rinv
+ where
+ rho = p_composeL sigma tau tinv
+ rinv = p_composeR tinv sinv
+
+-- | Invert a permutation. O(1).
+perm_invert :: Permutation -> Permutation
+perm_invert (Permutation sigma sinv) = Permutation sinv sigma
+
+-- | Apply a permutation to an atom. O(1).
+perm_apply_atom :: Permutation -> Atom -> Atom
+perm_apply_atom (Permutation sigma sinv) = p_apply_atom sigma
+
+-- | Swap /a/ and /b/. O(1).
+perm_swap :: Atom -> Atom -> Permutation
+perm_swap a b = Permutation sigma sigma
+ where
+ sigma = p_swap a b
+
+-- | Swap the given pairs of atoms.
+perm_swaps :: [(Atom,Atom)] -> Permutation
+perm_swaps [] = perm_identity
+perm_swaps ((a,b):xs) = perm_swap a b `perm_composeL` perm_swaps xs
+
+-- | The domain of a permutation. O(/n/).
+perm_domain :: Permutation -> [Atom]
+perm_domain (Permutation sigma sinv) = p_domain sigma
+
+-- | Make a permutation from a list of swaps. This is mostly useful
+-- for testing. O(/n/).
+perm_of_swaps :: [(Atom, Atom)] -> Permutation
+perm_of_swaps xs = aux xs where
+ aux [] = perm_identity
+ aux ((a,b):t) = perm_swap a b `perm_composeL` perm_of_swaps t
+
+-- | Turn a permutation into a list of swaps. This is mostly useful
+-- for testing. O(/n/).
+swaps_of_perm :: Permutation -> [(Atom, Atom)]
+swaps_of_perm sigma = [ y | Just y <- ys ]
+ where
+ domain = perm_domain sigma
+ (tau, ys) = mapAccumL f sigma domain
+ f acc a
+ | a == b = (acc', Nothing)
+ | otherwise = (acc', Just (a, b))
+ where
+ b = perm_apply_atom acc a
+ acc' = perm_composeL (perm_swap a b) acc
+
diff --git a/Nominal/Unsafe.hs b/Nominal/Unsafe.hs
new file mode 100644
index 0000000..a97ab28
--- /dev/null
+++ b/Nominal/Unsafe.hs
@@ -0,0 +1,65 @@
+{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}
+
+-- | This module provides three primitive functions that use
+-- 'unsafePerformIO'. These functions are only safe if used correctly.
+-- How to use each function correctly is specified in its documentation.
+
+module Nominal.Unsafe where
+
+import Data.IORef
+import Data.Set (Set)
+import qualified Data.Set as Set
+import Data.Unique
+import System.IO.Unsafe (unsafePerformIO)
+
+import Nominal.ConcreteNames
+
+-- | A global variable holding a set of strings already used for free
+-- names.
+--
+-- The use of 'unsafePerformIO' in this function is safe, because it
+-- is only called once and serves to create a global reference cell.
+{-# NOINLINE global_used #-}
+global_used :: IORef (Set String)
+global_used = unsafePerformIO $ do
+ newIORef Set.empty
+
+-- | Create a globally new concrete name based on the given name
+-- suggestion. This ensures that fresh names have distinct names when
+-- they are not bound.
+global_new_io :: NameGen -> IO String
+global_new_io ng = do
+ used <- readIORef global_used
+ let n = rename_fresh used ng
+ writeIORef global_used (Set.insert n used)
+ return n
+
+-- | Create a globally new concrete name based on the given name
+-- suggestion. The use of 'unsafePerformIO' in this function is safe
+-- if the user respects the correctness conditions associated with the
+-- function 'with_fresh' and other analogous functions.
+{-# NOINLINE global_new #-}
+global_new :: NameGen -> String
+global_new ng = unsafePerformIO (global_new_io ng)
+
+-- | Perform a subcomputation in the presence of a globally unique
+-- value. This is similar to 'newUnique', but uses a continuation
+-- monad instead of the 'IO' monad. To ensure referential
+-- transparency, the unique value must not escape the function body.
+--
+-- The use of 'unsafePerformIO' in this function is safe if the user
+-- respects the correctness conditions associated with the function
+-- 'with_fresh' and other analogous functions.
+{-# NOINLINE with_unique #-}
+with_unique :: (Unique -> a) -> a
+with_unique k = unsafePerformIO $ do
+ x <- newUnique
+ return (k x)
+
+-- | Unsafely embed the 'IO' monad in a continuation monad. This is in
+-- general unsafe, but can be safe for certain kinds of 'IO'
+-- computation if the continuation satisfies a correctness condition.
+unsafe_with :: IO a -> (a -> b) -> b
+unsafe_with comp k = unsafePerformIO $ do
+ a <- comp
+ return (k a)
diff --git a/Setup.hs b/Setup.hs
new file mode 100644
index 0000000..9a994af
--- /dev/null
+++ b/Setup.hs
@@ -0,0 +1,2 @@
+import Distribution.Simple
+main = defaultMain
diff --git a/examples/CustomInstances.hs b/examples/CustomInstances.hs
new file mode 100644
index 0000000..1f9657c
--- /dev/null
+++ b/examples/CustomInstances.hs
@@ -0,0 +1,109 @@
+{-# LANGUAGE ApplicativeDo #-}
+
+-- | This file illustrates how to write manual instances for
+-- 'Nominal', 'NominalSupport', 'NominalShow', and 'Bindable'.
+--
+-- Note: this is usually unnecessary, as these instances can be
+-- derived. See "GenericInstances" for how to derive these instances
+-- automatically.
+
+import Nominal
+import Prelude hiding ((.))
+
+-- ----------------------------------------------------------------------
+-- * Example 1: MyTree
+
+data MyTree a = Leaf | Branch a (MyTree a) (MyTree a)
+
+instance (Nominal a) => Nominal (MyTree a) where
+ π • Leaf = Leaf
+ π • (Branch a l r) = Branch (π • a) (π • l) (π • r)
+
+instance (NominalSupport a) => NominalSupport (MyTree a) where
+ support Leaf = support ()
+ support (Branch a l r) = support (a, l, r)
+
+instance (NominalShow a) => NominalShow (MyTree a) where
+ showsPrecSup sup d Leaf = showString "Leaf"
+ showsPrecSup sup d (Branch a l r) =
+ showParen (d > 10) $
+ showString "Branch "
+ ∘ showsPrecSup sup 11 a
+ ∘ showString " "
+ ∘ showsPrecSup sup 11 l
+ ∘ showString " "
+ ∘ showsPrecSup sup 11 r
+
+instance (Bindable a) => Bindable (MyTree a) where
+ binding Leaf = do
+ pure Leaf
+ binding (Branch a l r) = do
+ a' <- binding a
+ l' <- binding l
+ r' <- binding r
+ pure (Branch a' l' r')
+
+-- ----------------------------------------------------------------------
+-- * Example 2: lambda calculus
+
+data Term = Var Atom | App Term Term | Abs (Bind Atom Term)
+
+instance Nominal Term where
+ π • Var x = Var (π • x)
+ π • App m n = App (π • m) (π • n)
+ π • Abs body = Abs (π • body)
+
+instance NominalSupport Term where
+ support (Var x) = support x
+ support (App m n) = support (m, n)
+ support (Abs body) = support body
+
+instance NominalShow Term where
+ showsPrecSup sup d (Var x) =
+ showParen (d > 10) $
+ showString "Var "
+ ∘ showsPrecSup sup 11 x
+ showsPrecSup sup d (App m n) =
+ showParen (d > 10) $
+ showString "App "
+ ∘ showsPrecSup sup 11 m
+ ∘ showString " "
+ ∘ showsPrecSup sup 11 n
+ showsPrecSup sup d (Abs body) =
+ open_for_printing sup body $ \x m sup ->
+ showParen (d > 10) $
+ showString "Abs ("
+ ∘ showsPrecSup sup 6 x
+ ∘ showString " . "
+ ∘ showsPrecSup sup 5 m
+ ∘ showString ")"
+
+instance Show Term where
+ showsPrec = nominal_showsPrec
+
+-- It does not make sense to define a 'Binable' instance for lambda
+-- terms, since lambda terms cannot be used as binders.
+
+-- ----------------------------------------------------------------------
+-- * Example 3: basic types
+
+-- $ A type is /basic/ or /non-nominal/ if its elements cannot contain
+-- atoms.
+
+data MyBaseType = MyString String | MyInt Int
+ deriving (Show)
+
+instance Nominal MyBaseType where
+ (•) = basic_action
+
+instance NominalSupport MyBaseType where
+ support = basic_support
+
+instance NominalShow MyBaseType where
+ showsPrecSup = basic_showsPrecSup
+
+instance Bindable MyBaseType where
+ binding = basic_binding
+
+
+
diff --git a/examples/GenericInstances.hs b/examples/GenericInstances.hs
new file mode 100644
index 0000000..e2c1e57
--- /dev/null
+++ b/examples/GenericInstances.hs
@@ -0,0 +1,23 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DeriveAnyClass #-}
+
+-- | This file illustrates how to derive generic instances for
+-- 'Nominal', 'NominalSupport', 'NominalShow', and 'Bindable'.
+
+import Nominal
+import Prelude hiding ((.))
+
+-- ----------------------------------------------------------------------
+-- * Example 1: MyTree
+
+data MyTree a = Leaf | Branch a (MyTree a) (MyTree a)
+ deriving (Generic, Nominal, NominalSupport, NominalShow, Show, Bindable)
+
+-- ----------------------------------------------------------------------
+-- * Example 2: lambda calculus
+
+-- It does not make sense to derive a 'Binable' instance for lambda
+-- terms, since lambda terms cannot be used as binders.
+
+data Term = Var Atom | App Term Term | Abs (Bind Atom Term)
+ deriving (Generic, Nominal, NominalSupport, NominalShow, Show)
diff --git a/examples/Lambda.hs b/examples/Lambda.hs
new file mode 100644
index 0000000..327ae60
--- /dev/null
+++ b/examples/Lambda.hs
@@ -0,0 +1,112 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DeriveAnyClass #-}
+
+-- | An example of "Nominal": untyped lambda calculus.
+
+module Lambda where
+
+import Nominal
+import Prelude hiding ((.))
+import Data.Set (Set)
+import qualified Data.Set as Set
+
+-- ----------------------------------------------------------------------
+-- * Terms
+
+data V
+instance AtomKind V
+type Variable = AtomOfKind V
+
+-- | The type of lambda terms, up to alpha-equivalence.
+data Term = Var Variable | App Term Term | Abs (Bind Variable Term)
+ deriving (Eq, Generic, Nominal, NominalSupport, NominalShow, Show)
+
+-- | A convenience constructor for abstractions. This allows us to
+-- write @lam (\x -> App x x)@ instead of @Abs (x.App (Var x) (Var x))@
+lam :: (Term -> Term) -> Term
+lam f = with_fresh (\x -> Abs (x . f (Var x)))
+
+-- | A version of 'lam' that permits us to suggest a name for the
+-- bound variable.
+lam_named :: String -> (Term -> Term) -> Term
+lam_named n f = with_fresh_named n (\x -> Abs (x . f (Var x)))
+
+-- | An alternative syntax for 'App'.
+(@@) :: Term -> Term -> Term
+m @@ n = App m n
+
+infixl 9 @@
+
+-- ----------------------------------------------------------------------
+-- * Substitution
+
+-- | Substitution. Note that it is capture avoiding!
+-- 'subst' /m/ /x/ /n/ substitutes /m/ for 'Var' /x/ in /n/.
+subst :: Term -> Variable -> Term -> Term
+subst m x (Var y)
+ | x == y = m
+ | otherwise = Var y
+subst m x (App t s) = App (subst m x t) (subst m x s)
+subst m x (Abs body) = open body (\y s -> Abs (y . subst m x s))
+
+-- ----------------------------------------------------------------------
+-- * Free variables
+
+-- | Free variables.
+fv :: Term -> Set Variable
+fv (Var x) = Set.singleton x
+fv (App m n) = fv m `Set.union` fv n
+fv (Abs t) = open t (\x s -> Set.delete x (fv s))
+
+-- ----------------------------------------------------------------------
+-- * Evaluation
+
+-- | Beta-reduction to normal form.
+reduce :: Term -> Term
+reduce (Var x) = Var x
+reduce (App m n) =
+ case reduce m of
+ Abs t -> open t (\x s -> reduce (subst n x s))
+ m' -> App m' (reduce n)
+reduce (Abs t) = open t (\x s -> Abs (x.reduce s))
+
+-- ----------------------------------------------------------------------
+-- * Some example terms
+
+-- | Church numeral zero.
+z :: Term
+z = lam_named "s" $ \s -> lam_named "z" $ \z -> z
+
+-- | Successor of Church numeral.
+s :: Term
+s = lam $ \n -> lam_named "s" $ \s -> lam_named "z" $ \z -> s @@ (n @@ s @@ z)
+
+-- | Addition of Church numerals.
+plus :: Term
+plus = lam $ \n -> lam $ \m -> n @@ s @@ m
+
+-- | Multiplication of Church numerals.
+times :: Term
+times = lam $ \n -> lam $ \m -> n @@ (plus @@ m) @@ z
+
+-- | The Church numeral /n/. This function demonstrates a use of
+-- 'with_fresh' to build lambda terms from names.
+church :: Integer -> Term
+church n =
+ with_fresh_named "s" $ \s ->
+ with_fresh_named "z" $ \z ->
+ Abs (s . Abs (z . aux n (Var s) (Var z)))
+ where
+ aux n s z
+ | n <= 0 = z
+ | otherwise = s @@ (aux (n-1) s z)
+
+-- | Another example of a recursively built term.
+multilam :: Integer -> Term -> Term
+multilam 0 t = t
+multilam n t = lam (\x -> multilam (n-1) t)
+
+-- | Another example of a recursively built term.
+nested :: Integer -> Term -> Term
+nested 0 t = t
+nested n t = lam (\x -> nested (n-1) (t @@ x))
diff --git a/examples/Minimal.hs b/examples/Minimal.hs
new file mode 100644
index 0000000..d1cc334
--- /dev/null
+++ b/examples/Minimal.hs
@@ -0,0 +1,19 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DeriveAnyClass #-}
+
+-- | A minimal example illustrating the "Nominal" library.
+
+import Nominal
+import Prelude hiding ((.))
+
+-- | Untyped lambda terms, up to alpha-equivalence.
+data Term = Var Atom | App Term Term | Abs (Bind Atom Term)
+ deriving (Generic, Nominal)
+
+-- | Capture-avoiding substitution.
+subst :: Term -> Atom -> Term -> Term
+subst m x (Var y)
+ | x == y = m
+ | otherwise = Var y
+subst m x (App t s) = App (subst m x t) (subst m x s)
+subst m x (Abs body) = open body (\y s -> Abs (y . subst m x s))
diff --git a/nominal.cabal b/nominal.cabal
new file mode 100644
index 0000000..aef5959
--- /dev/null
+++ b/nominal.cabal
@@ -0,0 +1,82 @@
+-- The name of the package.
+name: nominal
+
+-- The package version. See the Haskell package versioning policy (PVP)
+-- for standards guiding when and how versions should be incremented.
+-- http://www.haskell.org/haskellwiki/Package_versioning_policy
+-- PVP summary: +-+------- breaking API changes
+-- | | +----- non-breaking API additions
+-- | | | +--- code changes with no API change
+version: 0.1.0.0
+
+-- A short (one-line) description of the package.
+synopsis: Binders and alpha-equivalence made easy
+
+-- A longer description of the package.
+description:
+
+ An efficient and easy-to-use library for defining datatypes with
+ binders, and automatically handling bound variables and
+ alpha-equivalence. It is based on Gabbay and Pitts's theory of
+ nominal sets.
+
+-- URL for the project homepage or repository.
+-- homepage:
+
+-- The license under which the package is released.
+license: GPL-3
+
+-- The file containing the license text.
+license-file: LICENSE
+
+-- The package author(s).
+author: Peter Selinger
+
+-- An email address to which users can send suggestions, bug reports, and
+-- patches.
+maintainer: selinger@mathstat.dal.ca
+
+-- A copyright notice.
+copyright: Copyright (c) 2016-2018 Peter Selinger
+
+-- A classification category for future use by the package catalogue
+-- Hackage. These categories have not yet been specified, but the
+-- upper levels of the module hierarchy make a good start.
+category: Language, Generics, Compilers/Interpreters
+
+-- The type of build used by this package.
+build-type: Simple
+
+-- Constraint on the version of Cabal needed to build this package.
+cabal-version: 1.24
+
+-- A list of additional files to be included in source distributions
+-- built with setup sdist.
+extra-source-files: ChangeLog
+ examples/Minimal.hs
+ examples/Lambda.hs
+ examples/GenericInstances.hs
+ examples/CustomInstances.hs
+
+library
+ -- Modules exported by the library.
+ exposed-modules: Nominal,
+ Nominal.ConcreteNames,
+ Nominal.Unsafe,
+ Nominal.Atom,
+ Nominal.Permutation,
+ Nominal.Nominal,
+ Nominal.NominalSupport,
+ Nominal.NominalShow,
+ Nominal.Bindable,
+ Nominal.Atomic,
+ Nominal.Generics
+
+ -- Modules included in this library but not exported.
+ -- other-modules:
+
+ -- Other library packages from which modules are imported.
+ build-depends: base >= 4.5 && < 5,
+ containers >= 0.5
+
+ default-language: Haskell2010