conditional-restriction-parser (empty) → 0.1.0.4
raw patch · 30 files changed
+2258/−0 lines, 30 filesdep +QuickCheckdep +basedep +cmdargssetup-changed
Dependencies added: QuickCheck, base, cmdargs, conditional-restriction-parser, hourglass, hspec
Files
- ChangeLog.md +3/−0
- LICENSE.md +660/−0
- README.md +80/−0
- Setup.hs +2/−0
- app/Main.hs +111/−0
- conditional-restriction-parser.cabal +92/−0
- src/ConditionalRestriction.hs +65/−0
- src/ConditionalRestriction/Evaluate.hs +15/−0
- src/ConditionalRestriction/Internal/Evaluate.hs +190/−0
- src/ConditionalRestriction/Internal/Parse/OpeningHoursParser.hs +84/−0
- src/ConditionalRestriction/Internal/Parse/ParserLib.hs +101/−0
- src/ConditionalRestriction/Internal/Parse/RestrictionParser.hs +53/−0
- src/ConditionalRestriction/Parse.hs +41/−0
- src/ConditionalRestriction/Parse/AST.hs +95/−0
- src/ConditionalRestriction/Parse/InputData.hs +32/−0
- src/ConditionalRestriction/Parse/InputDataParser.hs +49/−0
- src/ConditionalRestriction/Parse/OpeningHoursParser.hs +4/−0
- src/ConditionalRestriction/Parse/ParserLib.hs +4/−0
- src/ConditionalRestriction/Parse/RestrictionParser.hs +8/−0
- src/ConditionalRestriction/Result.hs +38/−0
- test/Arbitrary/ConditionalRestriction/Parse/AST.hs +72/−0
- test/Arbitrary/ConditionalRestriction/Parse/InputData.hs +7/−0
- test/ConditionalRestriction/EvaluateSpec.hs +141/−0
- test/ConditionalRestriction/Parse/InputDataParserSpec.hs +26/−0
- test/ConditionalRestriction/Parse/OpeningHoursParserSpec.hs +43/−0
- test/ConditionalRestriction/Parse/ParserLibSpec.hs +125/−0
- test/ConditionalRestriction/Parse/RestrictionParserSpec.hs +47/−0
- test/ConditionalRestrictionSpec.hs +28/−0
- test/IntegrationSpec.hs +41/−0
- test/Spec.hs +1/−0
+ ChangeLog.md view
@@ -0,0 +1,3 @@+# Changelog for conditional-restriction-parser++## Unreleased changes
+ LICENSE.md view
@@ -0,0 +1,660 @@+### GNU AFFERO GENERAL PUBLIC LICENSE++Version 3, 19 November 2007++Copyright (C) 2007 Free Software Foundation, Inc.+<https://fsf.org/>++Everyone is permitted to copy and distribute verbatim copies of this+license document, but changing it is not allowed.++### Preamble++The GNU Affero General Public License is a free, copyleft license for+software and other kinds of works, specifically designed to ensure+cooperation with the community in the case of network server software.++The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+our General Public Licenses are 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.++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.++Developers that use our General Public Licenses protect your rights+with two steps: (1) assert copyright on the software, and (2) offer+you this License which gives you legal permission to copy, distribute+and/or modify the software.++A secondary benefit of defending all users' freedom is that+improvements made in alternate versions of the program, if they+receive widespread use, become available for other developers to+incorporate. Many developers of free software are heartened and+encouraged by the resulting cooperation. However, in the case of+software used on network servers, this result may fail to come about.+The GNU General Public License permits making a modified version and+letting the public access it on a server without ever releasing its+source code to the public.++The GNU Affero General Public License is designed specifically to+ensure that, in such cases, the modified source code becomes available+to the community. It requires the operator of a network server to+provide the source code of the modified version running there to the+users of that server. Therefore, public use of a modified version, on+a publicly accessible server, gives the public access to the source+code of the modified version.++An older license, called the Affero General Public License and+published by Affero, was designed to accomplish similar goals. This is+a different license, not a version of the Affero GPL, but Affero has+released a new version of the Affero GPL which permits relicensing+under this license.++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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.++Notwithstanding any other provision of this License, if you modify the+Program, your modified version must prominently offer all users+interacting with it remotely through a computer network (if your+version supports such interaction) an opportunity to receive the+Corresponding Source of your version by providing access to the+Corresponding Source from a network server at no charge, through some+standard or customary means of facilitating copying of software. This+Corresponding Source shall include the Corresponding Source for any+work covered by version 3 of the GNU General Public License that is+incorporated pursuant to the following paragraph.++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 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 work with which it is combined will remain governed by version+3 of the GNU General Public License.++#### 14. Revised Versions of this License.++The Free Software Foundation may publish revised and/or new versions+of the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.++ You should have received a copy of the GNU Affero General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper+mail.++If your software can interact with users remotely through a computer+network, you should also make sure that it provides a way for users to+get its source. For example, if your program is a web application, its+interface could display a "Source" link that leads users to an archive+of the code. There are many ways you could offer source, and different+solutions will be better for different programs; see section 13 for+the specific requirements.++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 AGPL, see <https://www.gnu.org/licenses/>.
+ README.md view
@@ -0,0 +1,80 @@+# Conditional Restriction Parser++This project includes a library that can be used to handle [OSM Conditional Restrictions]()+as well as a console-based application+that can be used for simple parsing and evaluation of conditional restrictions.++Both the library and the application are implemented in [Haskell](https://www.haskell.org/),+using [Stack](https://docs.haskellstack.org/en/stable/README/).+You can find the library code under `src/` and the application code under `app/`.++The library is designed to work with conditional restrictions as+[documented on 14. April 2022 on the OSM Wiki](https://wiki.openstreetmap.org/w/index.php?title=Conditional_restrictions&oldid=2310830).+Conditional restrictions also support OSM Opening Hours, for which only a subset+has been implemented in this project. The versions used are+[Key:opening_hours on 10. April 2022](https://wiki.openstreetmap.org/w/index.php?title=Key:opening_hours&oldid=2309608)+and [Key:opening_hours/specification on 04. November 2021](https://wiki.openstreetmap.org/w/index.php?title=Key:opening_hours/specification&oldid=2215648).++## Compiling the project++To compile the current state of the project, you'll need a working [Stack](https://docs.haskellstack.org/en/stable/README/)+setup and a working [GHC](https://www.haskell.org/ghc/) setup. The easiest way to set those both up is+probably with the [GHCup](https://www.haskell.org/ghcup/) tool.++Following versions have been found to be working for this project:+- GHCup v0.1.17.7 (newer probably possible)+- Stack v2.7.5 (newer probably possible)+- GHC v9.0.2 (should match your installation)++The build has only been tested on (Manjaro) Linux, but other operating systems+should work, as long as this setup is present. All you need to do in order to+compile the library and the application is to execute++``` sh+stack build+```++on a shell of your choice (Stack needs to be in your+[$PATH](https://linuxconfig.org/linux-path-environment-variable)) in the project+folder. Stack will output something like this:++```+Installing library in /home/user/workspace/conditional-restriction-parser/.stack-work/install/x86_64-linux-tinfo6/577aef19c282e0a36f2ce11fb38f5391ea06983467b015a6bfb319f9dd99acfe/9.0.2/lib/x86_64-linux-ghc-9.0.2/conditional-restriction-parser-0.1.0-45ZsUYVvY6oL6ghNWUuJIJ+Installing executable conditional-restriction-parser-exe in /home/user/workspace/conditional-restriction-parser/.stack-work/install/x86_64-linux-tinfo6/577aef19c282e0a36f2ce11fb38f5391ea06983467b015a6bfb319f9dd99acfe/9.0.2/bin+Registering library for conditional-restriction-parser-0.1.0..+```++From which you can see where the built library and where the built application+was stored. If you want to install the application in your $PATH, you can+execute++``` sh+stack install+```++which will install the built application in a dedicated directory. The executable will be named `conditional-restriction-parser-exe`.++## Developer Setup++If you want to develop new features or fix a bug, you'll need to set up a+developement environment. First, follow the steps for [compiling the+project](#compiling-the-project). Any IDE that supports Haskell+works, but this project has been developed with [Doom+Emacs](https://github.com/doomemacs/doomemacs),+[LSP](https://microsoft.github.io/language-server-protocol/)+and [HLS](https://haskell-language-server.readthedocs.io/en/latest/what-is-hls.html) version 1.6.1.0.+Please use [Ormolu](https://github.com/tweag/ormolu) for formatting your code if you want+to contribute your code to the project, this will guarantee consistent style.++Execute unit tests and integration tests using++```sh+stack test+```++in the project folder. If you want to check the test coverage, use++``` sh+stack test --coverage+stack hpc report .+```
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ app/Main.hs view
@@ -0,0 +1,111 @@+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE LambdaCase #-}++module Main where++import ConditionalRestriction (ID, Result (Err, Ok), Type (TBool, TNum, TTime), evaluate, needsData, parseRestriction)+import Control.Monad (unless, when)+import System.Console.CmdArgs+ ( CmdArgs,+ Data,+ Default (def),+ Mode,+ Typeable,+ argPos,+ args,+ auto,+ cmdArgsMode,+ cmdArgsRun,+ details,+ help,+ modes,+ name,+ program,+ summary,+ typ,+ (&=),+ )+import System.Exit (exitFailure)++data Program+ = Evaluate {restriction :: String, values :: [String]}+ | Parse {restriction :: String}+ | DataNeeded {restriction :: String}+ deriving (Show, Data, Typeable, Eq)++programModes :: Mode (CmdArgs Program)+programModes =+ cmdArgsMode $+ modes+ [ Evaluate+ { restriction = def &= typ "RESTRICTION" &= argPos 0,+ values = def &= typ "KEY=VALUE" &= args+ }+ &= auto+ &= help "Evaluate a conditional restriction based on data given in key=value format."+ &= details+ [ "Example usage: 'evaluate evaluate \"no @ (09:00-17:00 AND wet)\" time=\"2022-05-11 12:23\" wet=true'",+ "To check the data needed to evaluate a restriction use 'data-needed'.",+ "",+ "Values can be of types BOOL, NUM or TIME.",+ "Format of BOOL values: 'true'/'false'",+ "Examples of NUM values: '3', '10.04'",+ "Format of TIME values: 'YYYY-MM-DD hh:mm', e.g. '2022-05-10 22:15'"+ ],+ Parse+ { restriction = def &= typ "PRESTRICTION" &= argPos 0 -- due to a bug in cmdargs, sadly the type has to be named differently than in evaluate: https://github.com/ndmitchell/cmdargs/issues/67+ }+ &= help "Parse a conditional restriction and return its AST."+ &= details ["The AST is defined in the package ConditionalRestriction.Parse.AST."],+ DataNeeded+ { restriction = def &= typ "DRESTRICTION" &= argPos 0+ }+ &= name "data-needed"+ &= help "List the data needed to evaluate this conditional restriction."+ ]+ &= program "conditional-restriction-parser-exe"+ &= summary "Conditional Restriction Parser v0.1.0.0, (C) Lukas Buchli 2022"++main :: IO ()+main =+ cmdArgsRun programModes >>= \case+ Evaluate r kvs -> do+ kvs' <- mapM separate kvs+ case evaluate r kvs' of+ Ok Nothing -> putStrLn "This restriction does not match the given data. Output unknown."+ Ok (Just t) -> putStrLn t+ Err (msgs, neededs) -> do+ unless (null msgs) $ do+ putStrLn "Errors were encountered during evaluation:"+ mapM_ (putStrLn . (" - " ++)) msgs+ unless (null neededs) $ do+ putStrLn "The following data is required for evaluation but has not been provided:"+ mapM_ (putStrLn . (" - " ++) . showData) neededs+ exitFailure+ Parse r -> case parseRestriction r of+ Ok ast -> print ast+ Err msg -> do+ putStrLn msg+ exitFailure+ DataNeeded r -> case needsData r of+ Ok neededs -> mapM_ (putStrLn . showData) neededs+ Err msg -> do+ putStrLn msg+ exitFailure+ where+ separate s = case split '=' s of+ [k, v] -> return (k, v)+ _ -> do+ putStrLn $ "Expected " ++ s ++ " to be of format KEY=VALUE."+ exitFailure++split d (x : xs) | d == x = [] : split d xs+split d (x : xs) = case split d xs of+ (xs' : xss) -> (x : xs') : xss+ [] -> [[x]]+split d [] = []++showData :: (ID, Type) -> String+showData (id, TBool) = id ++ ": BOOL (e.g. '" ++ id ++ "=false')"+showData (id, TNum) = id ++ ": NUM (e.g. '" ++ id ++ "=3.0')"+showData (id, TTime) = id ++ ": TIME (e.g. '" ++ id ++ "=\"2022-05-10 12:35\"'"
+ conditional-restriction-parser.cabal view
@@ -0,0 +1,92 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.34.7.+--+-- see: https://github.com/sol/hpack++name: conditional-restriction-parser+version: 0.1.0.4+synopsis: Parser and interpreter of OpenStreetMap conditional restriction values+description: Please see the README on GitHub at <https://github.com/geometalab/conditional-restriction-parser#readme>+category: Parser+homepage: https://github.com/geometalab/conditional-restriction-parser#readme+bug-reports: https://github.com/geometalab/conditional-restriction-parser/issues+author: Lukas Buchli+maintainer: lukas.buchli@ost.ch+copyright: 2022 Lukas Buchli+license: AGPL-3+license-file: LICENSE.md+build-type: Simple+extra-source-files:+ README.md+ ChangeLog.md++source-repository head+ type: git+ location: https://github.com/geometalab/conditional-restriction-parser++library+ exposed-modules:+ ConditionalRestriction+ ConditionalRestriction.Evaluate+ ConditionalRestriction.Internal.Evaluate+ ConditionalRestriction.Internal.Parse.OpeningHoursParser+ ConditionalRestriction.Internal.Parse.ParserLib+ ConditionalRestriction.Internal.Parse.RestrictionParser+ ConditionalRestriction.Parse+ ConditionalRestriction.Parse.AST+ ConditionalRestriction.Parse.InputData+ ConditionalRestriction.Parse.InputDataParser+ ConditionalRestriction.Parse.OpeningHoursParser+ ConditionalRestriction.Parse.ParserLib+ ConditionalRestriction.Parse.RestrictionParser+ ConditionalRestriction.Result+ other-modules:+ Paths_conditional_restriction_parser+ hs-source-dirs:+ src+ build-depends:+ base >=4.7 && <5+ , cmdargs ==0.10.21+ , hourglass >=0.2.12 && <0.3+ default-language: Haskell2010++executable conditional-restriction-parser-exe+ main-is: Main.hs+ other-modules:+ Paths_conditional_restriction_parser+ hs-source-dirs:+ app+ ghc-options: -threaded -rtsopts -with-rtsopts=-N+ build-depends:+ base >=4.7 && <5+ , cmdargs ==0.10.21+ , conditional-restriction-parser+ , hourglass >=0.2.12 && <0.3+ default-language: Haskell2010++test-suite conditional-restriction-parser-test+ type: exitcode-stdio-1.0+ main-is: Spec.hs+ other-modules:+ Arbitrary.ConditionalRestriction.Parse.AST+ Arbitrary.ConditionalRestriction.Parse.InputData+ ConditionalRestriction.EvaluateSpec+ ConditionalRestriction.Parse.InputDataParserSpec+ ConditionalRestriction.Parse.OpeningHoursParserSpec+ ConditionalRestriction.Parse.ParserLibSpec+ ConditionalRestriction.Parse.RestrictionParserSpec+ ConditionalRestrictionSpec+ IntegrationSpec+ Paths_conditional_restriction_parser+ hs-source-dirs:+ test+ ghc-options: -threaded -rtsopts -with-rtsopts=-N+ build-depends:+ QuickCheck ==2.14.2+ , base >=4.7 && <5+ , cmdargs ==0.10.21+ , conditional-restriction-parser+ , hourglass >=0.2.12 && <0.3+ , hspec ==2.8.5+ default-language: Haskell2010
+ src/ConditionalRestriction.hs view
@@ -0,0 +1,65 @@+{-# LANGUAGE TupleSections #-}++-- |+-- The ConditionalRestriction library offers functionality for parsing and+-- evaluating of conditional restriction values+-- (see [OSM Wiki](https://wiki.openstreetmap.org/wiki/Conditional_restrictions)).+--+-- This module offers functions suitable for most basic use cases.+module ConditionalRestriction+ ( needsData,+ evaluate,+ parseRestriction,+ ID,+ Value (..),+ Type (..),+ Token,+ Result (..),+ ErrorMsg,+ )+where++import ConditionalRestriction.Internal.Evaluate+ ( ErrorMsg,+ result,+ )+import ConditionalRestriction.Internal.Parse.ParserLib (end, parse)+import ConditionalRestriction.Internal.Parse.RestrictionParser+ ( pConditionalRestriction,+ )+import ConditionalRestriction.Parse.AST+ ( ConditionalRestriction,+ Token,+ )+import ConditionalRestriction.Parse.InputData+ ( ID,+ Type (..),+ Value (..),+ )+import ConditionalRestriction.Parse.InputDataParser (pValue)+import ConditionalRestriction.Result (Result (..))+import Data.Bifunctor (Bifunctor (first))++-- | Takes a conditional restriction string and returns the data needed in order to evaluate this string.+-- If the conditional restriction couldn't be parsed,+-- an error message is returned instead.+needsData :: String -> Result ErrorMsg [(ID, Type)]+needsData s =+ parseRestriction s >>= \r -> case result [] r of+ Err (_, neededs) -> Ok neededs+ Ok _ -> Ok []++-- | Takes a conditional restriction string and some input data.+-- It returns the value as a token if any restriction condition was met, or 'Nothing' otherwise.+-- If there was a parsing error or a problem with the provided data, a list of error messages+-- and a list of needed data is returned.+evaluate :: String -> [(ID, String)] -> Result ([ErrorMsg], [(ID, Type)]) (Maybe Token)+evaluate s ds = do+ r <- first (\msg -> (["Parser error in restriction: " ++ msg], [])) $ parseRestriction s+ ds' <- first (\msg -> (["Parser error in data: " ++ msg], [])) $ mapM (\(id, d) -> (id,) . fst <$> parse (pValue <* end) d) ds+ result ds' r++-- | Takes a conditional restriction string and returns the corresponding AST.+-- Take a look at the "ConditionalRestriction.Parse.AST" module for AST manipulation.+parseRestriction :: String -> Result ErrorMsg ConditionalRestriction+parseRestriction = fmap fst . parse (pConditionalRestriction <* end)
+ src/ConditionalRestriction/Evaluate.hs view
@@ -0,0 +1,15 @@+-- | Functions to evaluate conditional restrictions.+module ConditionalRestriction.Evaluate+ ( ErrorMsg,+ result,+ fulfills,+ timeIn,+ )+where++import ConditionalRestriction.Internal.Evaluate+ ( ErrorMsg,+ fulfills,+ result,+ timeIn,+ )
+ src/ConditionalRestriction/Internal/Evaluate.hs view
@@ -0,0 +1,190 @@+{-# LANGUAGE LambdaCase #-}++-- | Functions to evaluate conditional restrictions.+module ConditionalRestriction.Internal.Evaluate where++import ConditionalRestriction.Parse.AST+ ( ComparisonOp (Eq, Gt, GtEq, Lt, LtEq),+ Condition (..),+ ConditionalRestriction (..),+ Expression (Expression),+ OpeningHours (..),+ RuleSequence (RuleSequence),+ RuleType (Additional, Normal),+ SelectorSequence+ ( TimeSel,+ TwentyFourSeven,+ WeekdaySel,+ WeekdayTime+ ),+ TimeSelector,+ TimeSpan (..),+ Token,+ WeekdayRange (SingleDay, WdayRange),+ WeekdaySelector,+ )+import ConditionalRestriction.Parse.InputData+ ( ID,+ Type (..),+ Value (..),+ )+import ConditionalRestriction.Result (Result (..))+import Data.Hourglass+ ( DateTime,+ TimeOfDay (TimeOfDay),+ WeekDay (Saturday, Sunday),+ getWeekDay,+ timeGetDate,+ timeGetTimeOfDay,+ )+import Data.List (nub)++-- | Plain text error message.+type ErrorMsg = String++-- | The 'result' function takes input data in the form of ('ID', 'Value') and a 'ConditionalRestriction' and returns+-- the result of that 'ConditionalRestriction' when applied to the input data given. If data needed for the evaluation+-- is missing or of the wrong type, it will return a list of error messages and a list of missing data types instead.+--+-- Note that this function will accept incomplete data if it is enough to evaluate the expression, but will always return+-- a complete list of needed data types.+result :: [(ID, Value)] -> ConditionalRestriction -> Result ([ErrorMsg], [(ID, Type)]) (Maybe Token)+result ds (ConditionalRestriction exprs) =+ find_r (\(Expression _ conds) -> all_r (fulfills ds) conds) (reverse exprs) >>= \case+ Nothing -> Ok Nothing+ Just (Expression tok _) -> Ok $ Just tok+ where+ find_r f (x : xs) = case f x of+ Ok True -> Ok $ Just x+ Ok False -> find_r f xs+ Err (msgs, needed) -> case find_r f xs of+ Err (msgs', needed') -> Err (msgs ++ msgs', nub $ needed ++ needed')+ Ok v -> Err (msgs, needed)+ find_r f [] = Ok Nothing++ all_r f (x : xs) = case f x of+ Ok True -> all_r f xs+ Ok False -> False <$ all_r f xs+ Err (Left msg) -> case all_r f xs of+ Ok _ -> Err ([msg], [])+ Err (msgs, neededs) -> Err (msg : msgs, neededs)+ Err (Right needed) -> case all_r f xs of+ Ok _ -> Err ([], [needed])+ Err (msgs, neededs) -> Err (msgs, needed : neededs)+ all_r f [] = Ok True++-- | The 'fulfills' function takes input data in the form of ('ID', 'Value') and a 'Condition' and returns+-- whether that condition is fulfilled. If some data is missing, it will return the missing data 'ID' and 'Type'+-- and if the given data is of the wrong type, it will return an error message.+fulfills :: [(ID, Value)] -> Condition -> Result (Either ErrorMsg (ID, Type)) Bool+fulfills ds (OH oh) = case lookup "time" ds of+ Just (VTime t) -> Ok $ timeIn t oh+ Just _ -> Err . Left $ "Incorrect input type for time"+ Nothing -> case oh of+ OpeningHours [RuleSequence _ TwentyFourSeven (Just o)] -> Ok o+ _ -> Err $ Right ("time", TTime)+fulfills ds (Comparison tok op val) = case lookup tok ds of+ Just (VNum d) -> Ok $ case op of+ Gt -> d > val+ Lt -> d < val+ GtEq -> d >= val+ LtEq -> d <= val+ Eq -> d == val+ Just _ -> Err . Left $ "Incorrect input type for " ++ tok+ Nothing -> Err $ Right (tok, TNum)+fulfills ds (Absolute tok) = case lookup tok ds of+ Just (VBool b) -> Ok b+ Just _ -> Err . Left $ "Incorrect input type for " ++ tok+ Nothing -> Err $ Right (tok, TBool)++-- | The 'timeIn' function returns wheter a 'DateTime' is within given 'OpeningHours'. Unknown values count as not+-- within the opening hours.+timeIn :: DateTime -> OpeningHours -> Bool+timeIn t oh =+ timeInSelector time (ohTimes oh !! fromEnum weekday)+ || timeExtendedInSelector time (ohTimes oh !! fromEnum previous_weekday)+ where+ date = timeGetDate t+ time = timeGetTimeOfDay t+ weekday = getWeekDay date+ previous_weekday = if weekday == minBound then maxBound else pred weekday++ohTimes :: OpeningHours -> [TimeSelector]+ohTimes (OpeningHours rs) = foldr set_time_ranges [[] | _ <- range Sunday Saturday] (reverse rs)+ where+ set_time_ranges (RuleSequence t TwentyFourSeven (Just o)) = map (integrate t o [Span min_time max_time])+ set_time_ranges (RuleSequence t (WeekdaySel wdrs) (Just o)) = mapDays (combineWeekdays wdrs) (integrate t o [Span min_time max_time])+ set_time_ranges (RuleSequence t (TimeSel ts) (Just o)) = map (integrate t o ts)+ set_time_ranges (RuleSequence t (WeekdayTime wdrs ts) (Just o)) = mapDays (combineWeekdays wdrs) (integrate t o ts)+ set_time_ranges _ = id+ min_time = TimeOfDay 00 00 00 0+ max_time = TimeOfDay 23 59 59 999999999+ integrate Normal = override+ integrate Additional = combine+ override True = const+ override False = \_ -> const []+ combine True = foldr addTimespan+ combine False = foldr subtractTimespan++timeInSelector :: TimeOfDay -> TimeSelector -> Bool+timeInSelector t = any match_t+ where+ match_t (Moment t') = t' == t+ match_t (Span t1 t2) = t >= t1 && (t <= t2 || t1 > t2)++timeExtendedInSelector :: TimeOfDay -> TimeSelector -> Bool+timeExtendedInSelector t = any match_t+ where+ match_t (Moment (TimeOfDay h' m' s' n')) = t == TimeOfDay (h' - 24) m' s' n'+ match_t (Span t1 t2) | t1 > t2 = t <= t2+ match_t (Span t1 (TimeOfDay h' m' s' n')) | h' >= 24 = t < TimeOfDay (h' - 24) m' s' n'+ match_t _ = False++addTimespan :: TimeSpan -> TimeSelector -> TimeSelector+addTimespan ts sel = add_timespan (explicitExtended ts) (map explicitExtended sel)+ where+ add_timespan (Moment t) sel@(Moment t' : ts) | t == t' = sel+ add_timespan (Moment t) (Moment t' : ts) = Moment t' : add_timespan (Moment t) ts+ add_timespan (Moment t) sel@(Span t1 t2 : ts) | t >= t1 && t <= t2 = sel+ add_timespan (Moment t) (Span t1 t2 : ts) = Span t1 t2 : add_timespan (Moment t) ts+ add_timespan (Span t1 t2) (Moment t : ts) | t >= t1 && t <= t2 = Span t1 t2 : ts+ add_timespan (Span t1 t2) (Moment t : ts) = Moment t : add_timespan (Span t1 t2) ts+ add_timespan (Span ta1 ta2) (Span tb1 tb2 : ts) | (tb1 <= ta2 && tb2 > ta1) || (ta1 <= tb2 && ta2 > tb1) = -- where overlaps+ Span (min ta1 tb1) (max ta2 tb2) : ts+ add_timespan (Span ta1 ta2) (Span tb1 tb2 : ts) = Span tb1 tb2 : add_timespan (Span ta1 ta2) ts+ add_timespan x [] = [x]++subtractTimespan :: TimeSpan -> TimeSelector -> TimeSelector+subtractTimespan ts sel = subtract_timespan (explicitExtended ts) (map explicitExtended sel)+ where+ subtract_timespan (Moment t) sel@(Moment t' : ts) | t == t' = ts+ subtract_timespan (Moment t) (Moment t' : ts) = Moment t' : subtract_timespan (Moment t) ts+ subtract_timespan (Moment t) sel@(Span t1 t2 : ts) | t >= t1 && t <= t2 = sel -- don't subtract single moments from time spans+ subtract_timespan (Moment t) (Span t1 t2 : ts) = Span t1 t2 : subtract_timespan (Moment t) ts+ subtract_timespan (Span t1 t2) (Moment t : ts) | t >= t1 && t <= t2 = subtract_timespan (Span t1 t2) ts+ subtract_timespan (Span t1 t2) (Moment t : ts) = Moment t : subtract_timespan (Span t1 t2) ts+ subtract_timespan (Span ta1 ta2) (Span tb1 tb2 : ts) | (tb1 < ta2 && tb2 > ta1) || (ta1 < tb2 && ta2 > tb1) =+ Span (min ta1 tb1) (max ta1 tb1) : Span (min ta2 tb2) (max ta2 tb2) : ts+ subtract_timespan (Span ta1 ta2) (Span tb1 tb2 : ts) | ta1 == tb1 && ta2 == tb2 = ts+ subtract_timespan (Span ta1 ta2) (Span tb1 tb2 : ts) | ta1 == tb1 = Span (min ta2 tb2) (max ta2 tb2) : ts+ subtract_timespan (Span ta1 ta2) (Span tb1 tb2 : ts) | ta2 == tb2 = Span (min ta1 tb1) (max ta1 tb1) : ts+ subtract_timespan (Span ta1 ta2) (Span tb1 tb2 : ts) = Span tb1 tb2 : subtract_timespan (Span ta1 ta2) ts+ subtract_timespan x [] = []++explicitExtended :: TimeSpan -> TimeSpan+explicitExtended (Span t1 t2@(TimeOfDay h m s n)) | t1 >= t2 = Span t1 (TimeOfDay (h + 24) m s n)+explicitExtended other = other++mapDays :: [WeekDay] -> (a -> a) -> [a] -> [a]+mapDays days f = zipWith (\d x -> (if d `elem` days then f x else x)) (range Sunday Saturday)++combineWeekdays :: WeekdaySelector -> [WeekDay]+combineWeekdays = nub . combine+ where+ combine (SingleDay day : wdrs) = day : combineWeekdays wdrs+ combine (WdayRange from to : wdrs) = range from to ++ combineWeekdays wdrs+ combine [] = []++range :: (Ord a, Enum a, Bounded a) => a -> a -> [a]+range a b | b < a = [a ..] ++ [minBound .. b]+range a b = [a .. b]
+ src/ConditionalRestriction/Internal/Parse/OpeningHoursParser.hs view
@@ -0,0 +1,84 @@+-- | Parser for opening hours (incomplete).+module ConditionalRestriction.Internal.Parse.OpeningHoursParser where++import ConditionalRestriction.Internal.Parse.ParserLib+ ( Parser,+ bint,+ noneOf,+ str,+ word,+ ws,+ )+import ConditionalRestriction.Parse.AST+ ( OHState,+ OpeningHours (..),+ RuleSequence (..),+ RuleType (..),+ SelectorSequence (..),+ TimeSelector,+ TimeSpan (..),+ WeekdayRange (..),+ WeekdaySelector,+ )+import Control.Applicative (Alternative (many, (<|>)), optional)+import Data.Hourglass (TimeOfDay (TimeOfDay), WeekDay (..))++-- | Parse opening hours, e.g. @"Di-Fr 08:00-20:00"@.+pOpeningHours :: Parser String OpeningHours+pOpeningHours = OpeningHours <$> ((:) <$> pRuleSequence Normal <*> many next_rule_sequence)+ where+ next_rule_sequence =+ word ";" *> pRuleSequence Normal+ <|> word "," *> pRuleSequence Additional++pRuleSequence :: RuleType -> Parser String RuleSequence+pRuleSequence t = RuleSequence t <$> pSelectorSequence <*> pRuleModifier++pRuleModifier :: Parser String OHState+pRuleModifier =+ ( Just False <$ (word "closed" <|> word "off")+ <|> Nothing <$ word "unknown"+ <|> Just True <$ (word "open" <|> ws)+ )+ <* optional pComment++pSelectorSequence :: Parser String SelectorSequence+pSelectorSequence =+ TwentyFourSeven <$ word "24/7"+ <|> (WeekdayTime <$> pWeekdaySelector <*> pTimeSelector)+ <|> (WeekdaySel <$> pWeekdaySelector)+ <|> (TimeSel <$> pTimeSelector)++pWeekdaySelector :: Parser String WeekdaySelector+pWeekdaySelector = (:) <$> pWeekdayRange <*> many (word "," *> pWeekdayRange)++pTimeSelector :: Parser String TimeSelector+pTimeSelector = (:) <$> pTimeSpan <*> many (word "," *> pTimeSpan)++pWeekdayRange :: Parser String WeekdayRange+pWeekdayRange =+ WdayRange <$> pWday <*> (word "-" *> pWday)+ <|> SingleDay <$> pWday++pWday :: Parser String WeekDay+pWday =+ Sunday <$ word "Su"+ <|> Monday <$ word "Mo"+ <|> Tuesday <$ word "Tu"+ <|> Wednesday <$ word "We"+ <|> Thursday <$ word "Th"+ <|> Friday <$ word "Fr"+ <|> Saturday <$ word "Sa"++pTimeSpan :: Parser String TimeSpan+pTimeSpan =+ (Span <$> pTime False <*> (word "-" *> pTime True))+ <|> Moment <$> pTime False++pTime :: Bool -> Parser String TimeOfDay+pTime extended = (\h m -> TimeOfDay (fromIntegral h) (fromIntegral m) 0 0) <$> p_hour <*> (str ":" *> bint 59)+ where+ p_hour = if extended then bint 48 else bint 24++pComment :: Parser String String+pComment = str "\"" *> many (noneOf "\"") <* word "\""
+ src/ConditionalRestriction/Internal/Parse/ParserLib.hs view
@@ -0,0 +1,101 @@+{-# LANGUAGE LambdaCase #-}++-- | Parsing library. Implements a simple 'Parser' type, and some basic parsers, e.g. 'ws', 'dbl'.+module ConditionalRestriction.Internal.Parse.ParserLib where++import ConditionalRestriction.Result (Result (..))+import Control.Applicative (Alternative (empty, many, (<|>)))+import Control.Monad (replicateM, (>=>))+import Data.Bifunctor (Bifunctor (first))++-- | A generic parser. Takes an input type @i@ and returns an output type @a@.+newtype Parser i a = Parser+ { parse :: i -> Result String (a, i)+ }++instance Functor (Parser i) where+ fmap f (Parser p) = Parser $ fmap (first f) . p++instance Applicative (Parser i) where+ pure x = Parser $ \i -> Ok (x, i)+ (Parser pf) <*> (Parser px) = Parser $ pf >=> \(f, i') -> first f <$> px i'++instance Alternative (Parser i) where+ empty = Parser $ \i -> Err "No parsing possibilities left."+ (Parser a) <|> (Parser b) = Parser $ \i -> case a i of+ res@(Ok _) -> res+ Err msg -> b i++instance Monad (Parser i) where+ return = pure+ (Parser pa) >>= f = Parser $ \i -> case pa i of+ Ok (a, i') -> parse (f a) i'+ Err msg -> Err msg++str :: String -> Parser String String+str s = Parser $ \i ->+ if take len i == s+ then Ok (s, drop len i)+ else Err $ "Input does not match '" ++ s ++ "': " ++ shorten 16 i+ where+ len = length s++anyOf :: [Char] -> Parser String Char+anyOf cs = Parser $ \case+ [] -> Err "Empty input."+ (i : is) ->+ if i `elem` cs+ then Ok (i, is)+ else Err $ show i ++ " does not match any of '" ++ cs ++ "'"++noneOf :: [Char] -> Parser String Char+noneOf cs = Parser $ \case+ [] -> Err "Empty input."+ (i : is) ->+ if i `elem` cs+ then Err $ show i ++ " matches '" ++ cs ++ "'"+ else Ok (i, is)++ws :: Parser String String+ws = many (anyOf "\t\n ")++word :: String -> Parser String String+word s = str s <* ws++tok :: Parser String String+tok = many (noneOf "\t\n ") <* ws++dbl :: Parser String Double+dbl = Parser $ \i -> case reads i of+ [(x, rem)] -> Ok (x, rem)+ _ -> Err $ "No double: " ++ shorten 16 i++bint :: Int -> Parser String Int+bint max =+ read <$> case digits max of+ [] -> str "0"+ (x : xs) ->+ (:) <$> anyOf ['0' .. d2c (x - 1)] <*> replicateM (length xs) (anyOf ['0' .. '9'])+ <|> (:) <$> anyOf [d2c x] <*> mapM (\x' -> anyOf ['0' .. d2c x']) xs+ where+ digits 0 = []+ digits x = digits (x `div` 10) ++ [x `mod` 10]+ d2c = head . show++end :: Parser String ()+end = Parser $ \case+ [] -> Ok ((), "")+ i -> Err $ "There is still input left: " ++ i++shorten :: Int -> String -> String+shorten len str+ | len > 3 =+ if length str > len+ then take (len - 3) str ++ "..."+ else str+shorten len str = take len str++strip :: String -> String+strip = drop_ws . reverse . drop_ws . reverse+ where+ drop_ws = dropWhile (`elem` "\t\n ")
+ src/ConditionalRestriction/Internal/Parse/RestrictionParser.hs view
@@ -0,0 +1,53 @@+-- | Parser for conditional restrictions.+module ConditionalRestriction.Internal.Parse.RestrictionParser where++import ConditionalRestriction.Internal.Parse.OpeningHoursParser+ ( pOpeningHours,+ )+import ConditionalRestriction.Internal.Parse.ParserLib+ ( Parser,+ anyOf,+ dbl,+ noneOf,+ strip,+ word,+ ws,+ )+import ConditionalRestriction.Parse.AST+ ( ComparisonOp (..),+ Condition (..),+ ConditionalRestriction (..),+ Expression (..),+ )+import Control.Applicative (Alternative (many, some, (<|>)))+import Data.Functor ()++-- | Parse conditional restrictions, e.g. @"90 \@ 18:00-22:00; 50 \@ wet"@.+pConditionalRestriction :: Parser String ConditionalRestriction+pConditionalRestriction = ConditionalRestriction <$> ((:) <$> pExpression <*> many (word ";" *> pExpression))++pExpression :: Parser String Expression+pExpression = Expression <$> (strip <$> many (noneOf "@")) <*> (word "@" *> pMultipleConditions)++pMultipleConditions :: Parser String [Condition]+pMultipleConditions =+ (word "(" *> pMultipleConditions <* word ")")+ <|> (:) <$> pCondition <*> many (word "AND" *> pCondition)++pCondition :: Parser String Condition+pCondition =+ (word "(" *> pCondition <* word ")")+ <|> (OH <$> pOpeningHours)+ <|> (Comparison <$> pIdentifier <*> pCompOperator <*> dbl <* ws)+ <|> (Absolute <$> pIdentifier)++pCompOperator :: Parser String ComparisonOp+pCompOperator =+ (GtEq <$ word ">=")+ <|> (LtEq <$ word "<=")+ <|> (Eq <$ word "=")+ <|> (Lt <$ word "<")+ <|> (Gt <$ word ">")++pIdentifier :: Parser String String+pIdentifier = some (anyOf $ ['a' .. 'z'] ++ ['_', '-']) <* ws
+ src/ConditionalRestriction/Parse.hs view
@@ -0,0 +1,41 @@+-- | This module reexports functions and types you are most likely to use from @ConditionalRestriction.Parse.*@.+module ConditionalRestriction.Parse+ ( Parser,+ parse,+ pConditionalRestriction,+ pCondition,+ pValue,+ pOpeningHours,+ ConditionalRestriction,+ Condition,+ OpeningHours,+ ID,+ Value (..),+ Type (..),+ Token,+ )+where++import ConditionalRestriction.Internal.Parse.OpeningHoursParser+ ( pOpeningHours,+ )+import ConditionalRestriction.Internal.Parse.ParserLib+ ( Parser,+ parse,+ )+import ConditionalRestriction.Internal.Parse.RestrictionParser+ ( pCondition,+ pConditionalRestriction,+ )+import ConditionalRestriction.Parse.AST+ ( Condition,+ ConditionalRestriction,+ OpeningHours,+ Token,+ )+import ConditionalRestriction.Parse.InputData+ ( ID,+ Type (..),+ Value (..),+ )+import ConditionalRestriction.Parse.InputDataParser (pValue)
+ src/ConditionalRestriction/Parse/AST.hs view
@@ -0,0 +1,95 @@+-- | AST for conditional restrictions and incomplete AST for opening hours.+module ConditionalRestriction.Parse.AST+ ( Token,+ ConditionalRestriction (..),+ Expression (..),+ Condition (..),+ ComparisonOp (..),+ OpeningHours (..),+ OHState,+ RuleType (..),+ RuleSequence (..),+ WeekdaySelector,+ TimeSelector,+ SelectorSequence (..),+ WeekdayRange (..),+ TimeSpan (..),+ )+where++import Data.Hourglass (TimeOfDay, WeekDay)++-- | A single token. Is used to represent values of any kind that the parser does not touch.+type Token = String++-- | AST representation of a conditional restriction.+newtype ConditionalRestriction = ConditionalRestriction [Expression]+ deriving (Eq, Show)++-- | AST representation of a conditional restriction expression, containing a value and conditions for that value+data Expression+ = Expression+ Token+ -- ^ The value+ [Condition]+ -- ^ The conditions. All conditions must be met when evaluating.+ deriving (Eq, Show)++-- | AST representation of a condition.+data Condition+ = -- | An 'OpeningHours' condition. When evaluating, the given time must be within those opening hours.+ OH OpeningHours+ | -- | A comparison. Looks something like @"weight > 3.0"@+ Comparison Token ComparisonOp Double+ | -- | An absolute condition, e.g. @"wet"@, @"disabled"@.+ Absolute Token+ deriving (Eq, Show)++-- | A comparison operator.+data ComparisonOp = Gt | Lt | GtEq | LtEq | Eq+ deriving (Eq, Show)++-- | AST representation of opening hours. Not complete.+newtype OpeningHours = OpeningHours [RuleSequence]+ deriving (Eq, Show)++-- | Opening hour state. True\/False if known to be open/closed, Nothing if unknown.+type OHState = Maybe Bool++-- | Type of opening hour rule.+data RuleType+ = -- | First rule or rules separated by ";".+ Normal+ | -- | Rules separated by ",".+ Additional+ deriving (Eq, Show)++-- | AST representation of a rule sequence.+data RuleSequence = RuleSequence RuleType SelectorSequence OHState+ deriving (Eq, Show)++-- | AST representation of a weekday selector (e.g. @"Sa-Di, Th"@).+type WeekdaySelector = [WeekdayRange]++-- | AST representation of a time selector (e.g. @"18:00-20:00, 21:00-03:00"@).+type TimeSelector = [TimeSpan]++-- | AST representation of a selector sequence (e.g. @"24/7"@, @"We-Su 18:00-20:00"@).+data SelectorSequence+ = TwentyFourSeven+ | WeekdaySel WeekdaySelector+ | TimeSel TimeSelector+ | WeekdayTime WeekdaySelector TimeSelector+ deriving (Eq, Show)++-- | AST representation of a weekday range.+data WeekdayRange+ = SingleDay WeekDay+ | WdayRange WeekDay WeekDay+ deriving (Eq, Show)++-- | AST representation of time span.+data TimeSpan+ = Moment TimeOfDay+ | Span TimeOfDay TimeOfDay+ deriving (Eq, Show)
+ src/ConditionalRestriction/Parse/InputData.hs view
@@ -0,0 +1,32 @@+-- | Input data types and values.+module ConditionalRestriction.Parse.InputData+ ( ID,+ Type (..),+ Value (..),+ )+where++import Data.Hourglass (DateTime)++-- | An identifier, identifying a value, e.g. @"weight"@.+type ID = String++-- | Input data type.+data Type+ = -- | Boolean type, e.g. value @"true"@.+ TBool+ | -- | Number type, e.g. value @"3.0"@.+ TNum+ | -- | Time type, e.g. value @"2022-05-10 18:00"@.+ TTime+ deriving (Eq, Show)++-- | Input data value, corresponding to input 'Type's.+data Value+ = -- | Boolean value, e.g. @"true"@.+ VBool Bool+ | -- | Number value, e.g. @"3.0"@.+ VNum Double+ | -- | Time value, e.g. @"2022-05-10 18:00"@.+ VTime DateTime+ deriving (Eq, Show)
+ src/ConditionalRestriction/Parse/InputDataParser.hs view
@@ -0,0 +1,49 @@+-- | Parsers for input data values.+module ConditionalRestriction.Parse.InputDataParser+ ( pValue,+ pBool,+ pNum,+ pTime,+ )+where++import ConditionalRestriction.Internal.Parse.ParserLib+ ( Parser,+ bint,+ dbl,+ str,+ )+import ConditionalRestriction.Parse.InputData (Value (..))+import Control.Applicative (Alternative ((<|>)))+import Control.Monad (replicateM)+import Data.Hourglass+ ( Date (Date),+ DateTime (DateTime),+ TimeOfDay (TimeOfDay),+ )++-- | Parses 'Value's. See 'pBool', 'pNum' and 'pTime' for formats.+pValue :: Parser String Value+pValue = pBool <|> pTime <|> pNum++-- | Parses boolean values. Possible values are @"true"@ and @"false"@.+pBool :: Parser String Value+pBool =+ VBool True <$ str "true"+ <|> VBool False <$ str "false"++-- | Parses numbers. Values can be with or without decimal places, i.e. @"5"@ or @"5.34"@.+pNum :: Parser String Value+pNum = VNum <$> dbl++-- | Parses time and date in the format @"YYYY-MM-DD hh:mm"@.+pTime :: Parser String Value+pTime = VTime <$> (DateTime <$> p_date <*> (str " " *> p_time))+ where+ p_date = Date <$> p_year <*> (str "-" *> p_month) <*> (str "-" *> p_day)+ p_time = (\h m -> TimeOfDay (fromIntegral h) (fromIntegral m) 0 0) <$> bint 24 <*> (str ":" *> bint 59)+ p_year = bint 9999+ p_month = toEnum . (\x -> x - 1) <$> bint 12+ p_day = bint 31+ concat s c = s ++ [c]+ pack x y = [x, y]
+ src/ConditionalRestriction/Parse/OpeningHoursParser.hs view
@@ -0,0 +1,4 @@+-- | Parser for opening hours (incomplete).+module ConditionalRestriction.Parse.OpeningHoursParser (pOpeningHours) where++import ConditionalRestriction.Internal.Parse.OpeningHoursParser (pOpeningHours)
+ src/ConditionalRestriction/Parse/ParserLib.hs view
@@ -0,0 +1,4 @@+-- | Parsing library. Implements a simple 'Parser' type.+module ConditionalRestriction.Parse.ParserLib (Parser, parse) where++import ConditionalRestriction.Internal.Parse.ParserLib (Parser, parse)
+ src/ConditionalRestriction/Parse/RestrictionParser.hs view
@@ -0,0 +1,8 @@+-- | Parser for conditional restrictions.+module ConditionalRestriction.Parse.RestrictionParser+ ( pConditionalRestriction,+ pCondition,+ )+where++import ConditionalRestriction.Internal.Parse.RestrictionParser (pCondition, pConditionalRestriction)
+ src/ConditionalRestriction/Result.hs view
@@ -0,0 +1,38 @@+-- | A simple result type. Similar to the 'Either' type, but tuned for results with an error type.+module ConditionalRestriction.Result+ ( Result (..),+ fromResult,+ )+where++import Data.Bifunctor (Bifunctor, bimap)++-- | The 'Result' type consists of an error type @e@ and a success type @a@.+data Result e a+ = Err e+ | Ok a+ deriving (Eq, Show)++instance Functor (Result e) where+ fmap f (Ok a) = Ok (f a)+ fmap _ (Err e) = Err e++instance Bifunctor Result where+ bimap f _ (Err e) = Err $ f e+ bimap _ f (Ok x) = Ok $ f x++instance Applicative (Result e) where+ pure = Ok+ (Ok f) <*> (Ok x) = Ok (f x)+ (Err f) <*> _ = Err f+ _ <*> (Err x) = Err x++instance Monad (Result e) where+ return = pure+ (Ok x) >>= f = f x+ (Err x) >>= _ = Err x++-- | 'Result' equivalent to 'Data.Maybe.fromMaybe'.+fromResult :: a -> Result e a -> a+fromResult _ (Ok x) = x+fromResult x (Err _) = x
+ test/Arbitrary/ConditionalRestriction/Parse/AST.hs view
@@ -0,0 +1,72 @@+module Arbitrary.ConditionalRestriction.Parse.AST where++import ConditionalRestriction.Parse.AST+ ( ComparisonOp (..),+ Condition (..),+ ConditionalRestriction (..),+ Expression (..),+ OpeningHours (OpeningHours),+ RuleSequence (RuleSequence),+ RuleType (..),+ SelectorSequence (..),+ TimeSpan (..),+ WeekdayRange (..),+ )+import Control.Applicative (Alternative (some))+import Data.Hourglass (TimeOfDay (TimeOfDay), WeekDay (Saturday, Sunday))+import Data.Maybe (maybeToList)+import Test.QuickCheck+ ( Arbitrary (arbitrary),+ elements,+ listOf,+ oneof,+ )++instance Arbitrary ConditionalRestriction where+ arbitrary = fmap ConditionalRestriction $ (:) <$> arbitrary <*> (maybeToList <$> arbitrary)++instance Arbitrary Expression where+ arbitrary = Expression <$> elements ["yes", "private", "55 mph", "destination"] <*> listOf arbitrary++instance Arbitrary Condition where+ arbitrary =+ oneof+ [ OH . OpeningHours <$> listOf arbitrary,+ Comparison <$> elements ["wheight", "length", "width", "height", "wheels"] <*> arbitrary <*> arbitrary,+ Absolute <$> elements ["wet", "snow"]+ ]++instance Arbitrary RuleSequence where+ arbitrary = RuleSequence <$> elements [Normal, Additional] <*> arbitrary <*> arbitrary++instance Arbitrary SelectorSequence where+ arbitrary =+ oneof+ [ pure TwentyFourSeven,+ WeekdaySel <$> listOf arbitrary,+ TimeSel <$> listOf arbitrary,+ WeekdayTime <$> listOf arbitrary <*> listOf arbitrary+ ]++instance Arbitrary ComparisonOp where+ arbitrary = elements [Gt, Lt, GtEq, LtEq, Eq]++instance Arbitrary WeekdayRange where+ arbitrary =+ oneof+ [ SingleDay <$> arbitrary,+ WdayRange <$> arbitrary <*> arbitrary+ ]++instance Arbitrary WeekDay where+ arbitrary = elements (enumFromTo Sunday Saturday)++instance Arbitrary TimeSpan where+ arbitrary =+ oneof+ [ Moment <$> arbitrary,+ Span <$> arbitrary <*> arbitrary+ ]++instance Arbitrary TimeOfDay where+ arbitrary = TimeOfDay <$> elements [01 .. 23] <*> elements [00 .. 60] <*> elements [00 .. 60] <*> pure 0
+ test/Arbitrary/ConditionalRestriction/Parse/InputData.hs view
@@ -0,0 +1,7 @@+module Arbitrary.ConditionalRestriction.Parse.InputData where++import ConditionalRestriction.Parse.InputData (Type (..))+import Test.QuickCheck (Arbitrary (arbitrary), elements)++instance Arbitrary Type where+ arbitrary = elements [TBool, TNum, TTime]
+ test/ConditionalRestriction/EvaluateSpec.hs view
@@ -0,0 +1,141 @@+{-# LANGUAGE ScopedTypeVariables #-}++module ConditionalRestriction.EvaluateSpec where++import Arbitrary.ConditionalRestriction.Parse.AST ()+import ConditionalRestriction.Internal.Evaluate (addTimespan, fulfills, ohTimes, result, subtractTimespan, timeIn, timeInSelector)+import ConditionalRestriction.Parse.AST+ ( ComparisonOp (Gt),+ Condition (Absolute, Comparison),+ ConditionalRestriction (ConditionalRestriction),+ Expression (Expression),+ OpeningHours (OpeningHours),+ RuleSequence (RuleSequence),+ RuleType (Additional, Normal),+ SelectorSequence (..),+ TimeSpan (Span),+ WeekdayRange (SingleDay, WdayRange),+ )+import ConditionalRestriction.Parse.InputData+ ( Value (VBool, VNum),+ )+import ConditionalRestriction.Result (Result (Err, Ok))+import Data.Hourglass (Date (Date), DateTime (DateTime), Month (May), TimeOfDay (TimeOfDay), WeekDay (Friday, Monday, Sunday, Thursday, Tuesday, Wednesday))+import Test.Hspec (Spec, describe, it, shouldBe)+import Test.QuickCheck (Testable (property))++spec :: Spec+spec = do+ describe "result" $ do+ it "returns 100 on '120 @ wet; 100 @ snow' with 'wet' = True and 'snow' = True" $+ let ds = [("wet", VBool True), ("snow", VBool True)]+ restriction = ConditionalRestriction [Expression "120" [Absolute "wet"], Expression "100" [Absolute "snow"]]+ in result ds restriction `shouldBe` Ok (Just "100")+ it "returns nothing on '120 @ wet; 100 @ snow' with 'wet' = False and 'snow' = False" $+ let ds = [("wet", VBool False), ("snow", VBool False)]+ restriction = ConditionalRestriction [Expression "120" [Absolute "wet"], Expression "100" [Absolute "snow"]]+ in result ds restriction `shouldBe` Ok Nothing+ it "lists duplicate needs only once" $+ property $ \(cond :: Condition) ->+ let duplicate_restriction = ConditionalRestriction [Expression "open" [cond, cond], Expression "closed" [cond]]+ in case (result [] duplicate_restriction, fulfills [] cond) of+ (Err (_, [a]), Err (Right b)) -> a == b+ (Err _, _) -> False+ _ -> True+ describe "fulfills" $ do+ it "returns true on 'wet' with 'wet' = True" $+ fulfills [("wet", VBool True)] (Absolute "wet") `shouldBe` Ok True+ it "returns true on 'weight > 2' with 'weight' = 3" $+ fulfills [("weight", VNum 3)] (Comparison "weight" Gt 2) `shouldBe` Ok True+ describe "timeIn" $ do+ it "gets that 18:00 is within 24/7" $+ let time = DateTime (Date 2022 May 10) (TimeOfDay 18 00 00 00)+ span = OpeningHours [RuleSequence Normal TwentyFourSeven (Just True)]+ in timeIn time span `shouldBe` True+ it "gets that 18:00 is not within 24/7 off" $+ let time = DateTime (Date 2022 May 10) (TimeOfDay 18 00 00 00)+ span = OpeningHours [RuleSequence Normal TwentyFourSeven (Just False)]+ in timeIn time span `shouldBe` False+ it "gets that 18:00 is within 11:00-20:00" $+ let time = DateTime (Date 2022 May 10) (TimeOfDay 18 00 00 00)+ span = OpeningHours [RuleSequence Normal (TimeSel [Span (TimeOfDay 11 00 0 0) (TimeOfDay 20 00 0 0)]) (Just True)]+ in timeIn time span `shouldBe` True+ it "gets that 18:00 is not within 11:00-16:00" $+ let time = DateTime (Date 2022 May 10) (TimeOfDay 18 00 00 00)+ span = OpeningHours [RuleSequence Normal (TimeSel [Span (TimeOfDay 11 00 0 0) (TimeOfDay 16 00 0 0)]) (Just True)]+ in timeIn time span `shouldBe` False+ it "gets that We is within Mo-Th" $+ let time = DateTime (Date 2022 May 11) (TimeOfDay 18 00 00 00) -- wednesday+ span = OpeningHours [RuleSequence Normal (WeekdaySel [WdayRange Monday Thursday]) (Just True)]+ in timeIn time span `shouldBe` True+ it "gets that We is not within Fr-Su" $+ let time = DateTime (Date 2022 May 11) (TimeOfDay 18 00 00 00) -- wednesday+ span = OpeningHours [RuleSequence Normal (WeekdaySel [WdayRange Friday Sunday]) (Just True)]+ in timeIn time span `shouldBe` False+ it "can check extended time 11:00-30:00" $+ let time = DateTime (Date 2022 May 14) (TimeOfDay 04 00 00 00) -- saturday+ span = OpeningHours [RuleSequence Normal (WeekdayTime [SingleDay Friday] [Span (TimeOfDay 11 00 0 0) (TimeOfDay 30 00 0 0)]) (Just True)]+ in timeIn time span `shouldBe` True+ it "can check extended time 11:00-06:00" $+ let time = DateTime (Date 2022 May 14) (TimeOfDay 04 00 00 00) -- saturday+ span = OpeningHours [RuleSequence Normal (WeekdayTime [SingleDay Friday] [Span (TimeOfDay 11 00 0 0) (TimeOfDay 06 00 0 0)]) (Just True)]+ in timeIn time span `shouldBe` True+ it "returns false on 'Mo-Fr; Tue off' for tuesday" $+ let time = DateTime (Date 2022 May 10) (TimeOfDay 18 00 00 00) -- tuesday+ span =+ OpeningHours+ [ RuleSequence Normal (WeekdaySel [WdayRange Monday Friday]) (Just True),+ RuleSequence Normal (WeekdaySel [SingleDay Tuesday]) (Just False)+ ]+ in timeIn time span `shouldBe` False+ it "returns true on 'Mo-Fr off; Tue' for tuesday" $+ let time = DateTime (Date 2022 May 10) (TimeOfDay 18 00 00 00) -- tuesday+ span =+ OpeningHours+ [ RuleSequence Normal (WeekdaySel [WdayRange Monday Friday]) (Just False),+ RuleSequence Normal (WeekdaySel [SingleDay Tuesday]) (Just True)+ ]+ in timeIn time span `shouldBe` True+ describe "ohTimes" $ do+ it "returns only Mo and Mi for 'Mo-We; Tue off'" $+ let min = TimeOfDay 00 00 00 0+ max = TimeOfDay 23 59 59 999999999+ span =+ OpeningHours+ [ RuleSequence Normal (WeekdaySel [WdayRange Monday Wednesday]) (Just True),+ RuleSequence Normal (WeekdaySel [SingleDay Tuesday]) (Just False)+ ]+ in ohTimes span `shouldBe` [[], [Span min max], [], [Span min max], [], [], []]+ it "returns Mo, Tu, Mi for 'Tue off; Mo-We'" $+ let min = TimeOfDay 00 00 00 0+ max = TimeOfDay 23 59 59 999999999+ span =+ OpeningHours+ [ RuleSequence Normal (WeekdaySel [SingleDay Tuesday]) (Just False),+ RuleSequence Normal (WeekdaySel [WdayRange Monday Wednesday]) (Just True)+ ]+ in ohTimes span `shouldBe` [[], [Span min max], [Span min max], [Span min max], [], [], []]+ it "returns Tu for 'Tu off, Tu'" $+ let min = TimeOfDay 00 00 00 0+ max = TimeOfDay 23 59 59 999999999+ span =+ OpeningHours+ [ RuleSequence Normal (WeekdaySel [SingleDay Tuesday]) (Just False),+ RuleSequence Additional (WeekdaySel [SingleDay Tuesday]) (Just True)+ ]+ in ohTimes span `shouldBe` [[], [], [Span min max], [], [], [], []]+ it "returns Tu 00:00-10:00, 11:00-23:59 for 'Tu, Tu 10:00-11:00 off'" $+ let min = TimeOfDay 00 00 00 0+ ten = TimeOfDay 10 00 00 0+ eleven = TimeOfDay 11 00 00 0+ max = TimeOfDay 23 59 59 999999999+ span =+ OpeningHours+ [ RuleSequence Normal (WeekdaySel [SingleDay Tuesday]) (Just True),+ RuleSequence Additional (WeekdayTime [SingleDay Tuesday] [Span ten eleven]) (Just False)+ ]+ in ohTimes span `shouldBe` [[], [], [Span min ten, Span eleven max], [], [], [], []]+ describe "addTimespan" $ do+ it "is commutative" $ property $ \ts1 ts2 t -> timeInSelector t (addTimespan ts1 [ts2]) == timeInSelector t (addTimespan ts2 [ts1])+ describe "subtractTimespan" $ do+ it "is undone by addTimespan" $ property $ \ts1 ts2 t -> timeInSelector t (addTimespan ts1 (subtractTimespan ts1 [ts2])) == timeInSelector t (addTimespan ts1 [ts2])
+ test/ConditionalRestriction/Parse/InputDataParserSpec.hs view
@@ -0,0 +1,26 @@+module ConditionalRestriction.Parse.InputDataParserSpec where++import ConditionalRestriction.Parse+ ( Parser (parse),+ Value (VBool, VNum, VTime),+ pValue,+ )+import ConditionalRestriction.Parse.InputData+ ( Value (VBool, VNum, VTime),+ )+import ConditionalRestriction.Parse.InputDataParser (pValue)+import ConditionalRestriction.Result (Result (Ok))+import Data.Hourglass+ ( Date (Date),+ DateTime (DateTime),+ Month (May),+ TimeOfDay (TimeOfDay),+ )+import Test.Hspec (Spec, describe, it, shouldBe)++spec :: Spec+spec = do+ describe "pValue" $ do+ it "can parse a bool" $ parse pValue "true" `shouldBe` Ok (VBool True, "")+ it "can parse a number" $ parse pValue "2.0" `shouldBe` Ok (VNum 2, "")+ it "can parse a time" $ parse pValue "2022-05-10 12:23" `shouldBe` Ok (VTime $ DateTime (Date 2022 May 10) (TimeOfDay 12 23 0 0), "")
+ test/ConditionalRestriction/Parse/OpeningHoursParserSpec.hs view
@@ -0,0 +1,43 @@+module ConditionalRestriction.Parse.OpeningHoursParserSpec where++import ConditionalRestriction (Result (Ok))+import ConditionalRestriction.Internal.Parse.OpeningHoursParser+ ( pOpeningHours,+ pRuleModifier,+ pRuleSequence,+ pSelectorSequence,+ pWeekdaySelector,+ )+import ConditionalRestriction.Parse+ ( Parser (parse),+ pOpeningHours,+ )+import ConditionalRestriction.Parse.AST+ ( OpeningHours (OpeningHours),+ RuleSequence (RuleSequence),+ RuleType (Normal),+ SelectorSequence (TwentyFourSeven, WeekdaySel),+ WeekdayRange (SingleDay, WdayRange),+ )+import Data.Hourglass (WeekDay (Monday, Saturday, Thursday))+import Test.Hspec (Spec, describe, it, shouldBe)++spec :: Spec+spec = do+ describe "pOpeningHours" $ do+ it "can parse 'Mo'" $+ parse pOpeningHours "Mo" `shouldBe` Ok (OpeningHours [RuleSequence Normal (WeekdaySel [SingleDay Monday]) (Just True)], "")+ describe "pRuleSequence" $ do+ it "can parse 'Mo'" $+ parse (pRuleSequence Normal) "Mo" `shouldBe` Ok (RuleSequence Normal (WeekdaySel [SingleDay Monday]) (Just True), "")+ describe "pRuleModfier" $ do+ it "can parse 'closed'" $+ parse pRuleModifier "closed" `shouldBe` Ok (Just False, "")+ it "can parse closed plus a comment" $+ parse pRuleModifier "closed \"comment\"" `shouldBe` Ok (Just False, "")+ describe "pSelectorSequence" $ do+ it "can parse '24/7'" $+ parse pSelectorSequence "24/7" `shouldBe` Ok (TwentyFourSeven, "")+ describe "pWeekdaySelector" $ do+ it "can parse 'Mo - Th, Sa'" $+ parse pWeekdaySelector "Mo - Th, Sa" `shouldBe` Ok ([WdayRange Monday Thursday, SingleDay Saturday], "")
+ test/ConditionalRestriction/Parse/ParserLibSpec.hs view
@@ -0,0 +1,125 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++module ConditionalRestriction.Parse.ParserLibSpec where++-- cannot import Fn specifically++import ConditionalRestriction (Result (..))+import ConditionalRestriction.Internal.Parse.ParserLib+ ( Parser (parse),+ anyOf,+ bint,+ dbl,+ noneOf,+ shorten,+ str,+ strip,+ tok,+ word,+ ws,+ )+import Control.Applicative (Alternative (empty, (<|>)))+import Test.Hspec (Spec, describe, it, shouldBe, shouldSatisfy)+import Test.QuickCheck (property)+import Test.QuickCheck.Function -- cannot import Fn directly++{-# ANN spec "HLint: ignore Use <$>" #-} -- L31, ignore because <*> is the function we are testing, so we don't want to replace it with <$>+{-# ANN spec "HLint: ignore Alternative law, left identity" #-} -- L48, ignore because we are checking left identity+spec :: Spec+spec = do+ describe "Show (Result e)" $ do+ describe "show" $ do+ it "shows Ok 'test' as Ok 'test'" $ show (Ok "test" :: Result String String) `shouldBe` "Ok \"test\""+ describe "Applicative (Result e)" $ do+ describe "pure" $ do+ it "is the same as Ok" $ property $ \(x :: String) -> pure x == (Ok x :: Result String String)+ describe "(<*>)" $ do+ it "can apply any function" $ property $ \(Fn (f :: String -> String)) (x :: String) -> (pure f <*> pure x) == (pure (f x) :: Result String String)+ describe "Monad (Result e)" $ do+ describe "return" $ do+ it "is the same as pure" $ property $ \(x :: String) -> return x == (pure x :: Result String String)+ describe "Alternative (Parser i)" $ do+ describe "empty" $ do+ it "always throws an error" $+ property $ \i -> case parse (empty :: Parser String String) i of+ Err _ -> True+ Ok _ -> False+ describe "(<|>)" $ do+ it "Chooses second option if first is erroneous" $ property $ \i -> parse (empty <|> str "") i == parse (str "") i+ describe "Monad (Parser i)" $ do+ describe "return" $ do+ it "behaves the same as pure" $ property $ \(x :: String) (i :: String) -> parse (pure x) i == parse (return x) i+ describe "(>>=)" $ do+ it "parses the same as with applicatives" $+ property $ \(x :: String) i ->+ parse ((,) <$> str x <*> str x) i+ == parse+ ( do+ a <- str x+ b <- str x+ return (a, b)+ )+ i+ describe "str" $ do+ it "can parse any given string" $ property $ \(a, b) -> parse (str a) (a ++ b) == Ok (a, b)+ describe "anyOf" $ do+ it "can parse the char if it is in the list" $+ property $ \c s ->+ let shouldParse = c `elem` s+ in case parse (anyOf s) [c] of+ Err _ | not shouldParse -> True+ Ok (_, "") | shouldParse -> True+ _ -> False+ describe "noneOf" $ do+ it "can parse the char if it is not in the list" $+ property $ \c s ->+ let should_parse = c `notElem` s+ in case parse (noneOf s) [c] of+ Err _ | not should_parse -> True+ Ok (_, "") | should_parse -> True+ _ -> False+ describe "ws" $ do+ it "can parse a string containing only tabs, spaces and newlines" $+ let s = "\t \n "+ in parse ws s `shouldBe` Ok (s, "")+ it "can parse an empty string" $+ parse ws "" `shouldBe` Ok ("", "")+ it "never outputs a result other than whitespace" $+ property $ \s ->+ let contains_other = any (`notElem` "\t\n ")+ in case parse ws s of+ Err _ -> True+ Ok (res, _) -> not $ contains_other res+ describe "word" $ do+ it "can parse any given string followed by whitespace" $+ property $ \(a, b) ->+ case parse (word a) (a ++ " " ++ b) of+ Ok (a', _) -> a == a'+ _ -> False+ describe "tok" $ do+ it "can parse 'a b'" $ parse tok "a b" `shouldBe` Ok ("a", "b")+ describe "dbl" $ do+ it "can parse any double" $+ property $ \(d :: Double) ->+ parse dbl (show d) == Ok (d, "")+ it "throws an error on invalid value 'a'" $+ parse dbl "a" `shouldSatisfy` \case+ Err !_ -> True+ _ -> False+ describe "bint" $ do+ it "can parse its max value" $ property $ \i -> let i' = abs i in parse (bint i') (show i') == Ok (i', "")+ describe "shorten" $ do+ it "never outputs a string longer than given length" $+ property $ \len s ->+ length (shorten (abs len) s) <= abs len+ describe "strip" $ do+ it "never outputs a string starting with whitespace" $+ property $ \s -> case strip s of+ (c : cs) | c `elem` "\t\n " -> False+ _ -> True+ it "never outputs a string ending with whitespace" $+ property $ \s -> case reverse $ strip s of+ (c : cs) | c `elem` "\t\n " -> False+ _ -> True
+ test/ConditionalRestriction/Parse/RestrictionParserSpec.hs view
@@ -0,0 +1,47 @@+module ConditionalRestriction.Parse.RestrictionParserSpec where++import ConditionalRestriction (Result (Ok))+import ConditionalRestriction.Internal.Parse.RestrictionParser+ ( pCompOperator,+ pCondition,+ pConditionalRestriction,+ pExpression,+ pIdentifier,+ pMultipleConditions,+ )+import ConditionalRestriction.Parse+ ( Parser (parse),+ pCondition,+ pConditionalRestriction,+ )+import ConditionalRestriction.Parse.AST+ ( ComparisonOp (Gt, GtEq),+ Condition (Absolute, Comparison),+ ConditionalRestriction (ConditionalRestriction),+ Expression (Expression),+ )+import Test.Hspec (Spec, describe, it, shouldBe)++spec :: Spec+spec = do+ describe "pConditionalRestriction" $ do+ it "can parse '120 @ wet'" $+ parse pConditionalRestriction "120 @ wet" `shouldBe` Ok (ConditionalRestriction [Expression "120" [Absolute "wet"]], "")+ it "can parse '120 @ wet; 100 @ snow'" $+ parse pConditionalRestriction "120 @ wet; 100 @ snow"+ `shouldBe` Ok (ConditionalRestriction [Expression "120" [Absolute "wet"], Expression "100" [Absolute "snow"]], "")+ describe "pExpression" $ do+ it "can parse '120 @ wet'" $+ parse pExpression "120 @ wet" `shouldBe` Ok (Expression "120" [Absolute "wet"], "")+ describe "pMultipleConditions" $ do+ it "can parse a single condition" $+ parse pMultipleConditions "weight > 4.5" `shouldBe` Ok ([Comparison "weight" Gt 4.5], "")+ it "can parse two conditions" $+ parse pMultipleConditions "weight > 4.5 AND wet" `shouldBe` Ok ([Comparison "weight" Gt 4.5, Absolute "wet"], "")+ describe "pCondition" $ do+ it "can parse a wheight comparison" $ parse pCondition "weight > 4.5" `shouldBe` Ok (Comparison "weight" Gt 4.5, "")+ describe "pCompOperator" $ do+ it "can parse '>='" $ parse pCompOperator ">=" `shouldBe` Ok (GtEq, "")+ describe "pIdentifier" $ do+ it "accepts 'test-value' as an identifier" $ parse pIdentifier "test-value" `shouldBe` Ok ("test-value", "")+ it "does not accept 'test-value-1' as an identifier" $ parse pIdentifier "test-value-1" `shouldBe` Ok ("test-value-", "1")
+ test/ConditionalRestrictionSpec.hs view
@@ -0,0 +1,28 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE LambdaCase #-}++module ConditionalRestrictionSpec where++import ConditionalRestriction+ ( Result (Err, Ok),+ Type (TBool, TTime),+ evaluate,+ needsData,+ )+import ConditionalRestriction.Result (Result (Ok), fromResult)+import Test.Hspec (Spec, describe, it, shouldBe, shouldMatchList, shouldSatisfy)++spec :: Spec+spec = do+ describe "needsData" $ do+ it "returns an empty list if no information is required" $+ needsData "no @ 24/7" `shouldBe` Ok []+ describe "evaluate" $ do+ it "returns an error message when there is a syntax error in the restriction" $+ evaluate "no (at) 17:00-18:00" [] `shouldSatisfy` \case+ Err ([!_], []) -> True+ _ -> False+ it "returns an error message when there is a syntax error in the data" $+ evaluate "no @ 17:00-18:00" [("time", "2022-05-20 10::15")] `shouldSatisfy` \case+ Err ([!_], []) -> True+ _ -> False
+ test/IntegrationSpec.hs view
@@ -0,0 +1,41 @@+module IntegrationSpec where++import ConditionalRestriction+ ( Result (Ok),+ Type (TBool, TTime),+ evaluate,+ needsData,+ )+import ConditionalRestriction.Result (Result (Ok), fromResult)+import Test.Hspec (Spec, describe, it, shouldBe, shouldMatchList)++spec :: Spec+spec = do+ let term = "no @ (09:00-17:00); destination @ (09:00-17:00 AND disabled)"+ in describe term $ do+ it "returns 'time' and 'disabled' as needed data" $+ fromResult [] (needsData term) `shouldMatchList` [("time", TTime), ("disabled", TBool)]+ it "returns 'destination' on (time = 2022-05-10 10:00) and (disabled = true)" $+ evaluate term [("time", "2022-05-10 10:00"), ("disabled", "true")] `shouldBe` Ok (Just "destination")+ it "returns unknown on (time = 2022-05-10 08:00) and (disabled = true)" $+ evaluate term [("time", "2022-05-10 08:00"), ("disabled", "true")] `shouldBe` Ok Nothing+ let term = "120 @ (06:00-20:00); 80 @ wet"+ in describe term $ do+ it "returns 80 on (time = 2022-05-10 07:00) and (wet = true)" $+ evaluate term [("time", "2022-05-10 07:00"), ("wet", "true")] `shouldBe` Ok (Just "80")+ it "returns 120 on (time = 2022-05-10 07:00) and (wet = false)" $+ evaluate term [("time", "2022-05-10 07:00"), ("wet", "false")] `shouldBe` Ok (Just "120")+ let term = "delivery @ (07:00-11:00); customers @ (07:00-17:00)"+ in describe term $ do+ it "returns 'customers' on (time = 2022-05-10 07:00)" $+ evaluate term [("time", "2022-05-10 07:00")] `shouldBe` Ok (Just "customers")+ it "returns unknown on (time = 2022-05-10 06:00)" $+ evaluate term [("time", "2022-05-10 06:00")] `shouldBe` Ok Nothing+ let term = "foo @ (24/7); bar @ (Mo-Sa 10:00-12:00,13:00-20:00; Tu off); baz @ (Su-Tu 11:00-01:00, We-Th 11:00-03:00, Fr 11:00-06:00, Sa 11:00-07:00)"+ in describe term $ do+ it "returns 'foo' on (time = 2022-05-10 10:00 (Tuesday))" $+ evaluate term [("time", "2022-05-10 10:00")] `shouldBe` Ok (Just "foo")+ it "returns 'baz' on (time = 2022-05-10 11:00 (Tuesday))" $+ evaluate term [("time", "2022-05-10 11:00")] `shouldBe` Ok (Just "baz")+ it "returns 'bar' on (time = 2022-05-09 10:30 (Monday))" $+ evaluate term [("time", "2022-05-09 10:30")] `shouldBe` Ok (Just "bar")
+ test/Spec.hs view
@@ -0,0 +1,1 @@+{-# OPTIONS_GHC -F -pgmF hspec-discover #-}