diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..c497fa0a --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,5 @@ + + +------------- + +* [x] I publish this contribution under the [MIT License](https://opensource.org/license/mit). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index be8efc2c..060bb73a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,7 @@ on: env: RUSTFLAGS: -Dwarnings + RUSTDOCFLAGS: -Dwarnings jobs: rust_check: @@ -58,6 +59,7 @@ jobs: - name: Install toolchain uses: actions-rust-lang/setup-rust-toolchain@v1 with: + toolchain: stable components: rustfmt - name: cargo format @@ -138,6 +140,8 @@ jobs: - name: Install toolchain uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + toolchain: stable - name: cargo doc run: cargo doc --all-features @@ -178,7 +182,7 @@ jobs: uses: actions-rust-lang/setup-rust-toolchain@v1 - name: CLI - uses: GuillaumeFalourd/assert-command-line-output@v2 + uses: GuillaumeFalourd/assert-command-line-output@v2.4 with: command_line: cargo run -- p = 2\; p + 3 contains: 5 diff --git a/CHANGELOG.md b/CHANGELOG.md index ad4f7d95..411abaa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Change Log +## [11.3.1](https://github.com/ISibboI/evalexpr/compare/11.3.1...12.0.0) - ??? + +### Changed + + * `evalexpr` is now licensed under the GNU Affero General Public License Version 3 + ## [11.3.1](https://github.com/ISibboI/evalexpr/compare/11.3.0...11.3.1) - 2024-10-13 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index 0954f07d..dd204a2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -38,7 +38,6 @@ dependencies = [ "regex", "ron", "serde", - "serde_derive", ] [[package]] @@ -72,18 +71,18 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" -version = "1.0.69" +version = "1.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" +checksum = "b3e4daa0dcf6feba26f985457cdf104d4b4256fc5a09547140f3631bb076b19a" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.33" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] @@ -129,9 +128,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.2" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343" +checksum = "38200e5ee88914975b69f657f0801b6f6dccafd44fd9326302a4aaeecfacb1d8" dependencies = [ "aho-corasick", "memchr", @@ -141,9 +140,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.3" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" +checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" dependencies = [ "aho-corasick", "memchr", @@ -152,9 +151,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.2" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "ron" @@ -169,18 +168,18 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.192" +version = "1.0.210" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bca2a08484b285dcb282d0f67b26cadc0df8b19f8c12502c13d966bf9482f001" +checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.192" +version = "1.0.210" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6c7207fbec9faa48073f3e3074cbe553af6ea512d7c21ba46e434e70ea9fbc1" +checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f" dependencies = [ "proc-macro2", "quote", @@ -189,9 +188,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.39" +version = "2.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" +checksum = "89132cd0bf050864e1d38dc3bbc07a0eb8e7530af26344d3d2bbbef83499f590" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 06e3132d..e0cbba08 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,8 +9,8 @@ repository = "https://github.com/ISibboI/evalexpr.git" homepage = "https://github.com/ISibboI/evalexpr" documentation = "https://docs.rs/evalexpr" readme = "README.md" -license = "MIT" -edition = "2018" +license = "AGPL-3.0-only" +edition = "2021" rust-version = "1.65.0" [badges] @@ -23,19 +23,19 @@ name = "evalexpr" path = "src/lib.rs" [dependencies] -regex = { version = "1.5.5", optional = true} -serde = { version = "1.0.133", optional = true} -serde_derive = { version = "1.0.133", optional = true} -rand = { version = "0.8.5", optional = true} +regex = { version = "1.11.0", optional = true } +serde = { version = "1.0.210", features = ["derive"], optional = true } +rand = { version = "0.8.5", optional = true } [features] -serde_support = ["serde", "serde_derive"] -regex_support = ["regex"] +serde = ["dep:serde"] +regex = ["dep:regex"] +rand = ["dep:rand"] [dev-dependencies] -ron = "0.7.0" +ron = "0.7.1" rand = "0.8.5" rand_pcg = "0.3.1" [lints.rust] - unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] } \ No newline at end of file +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] } diff --git a/LICENSE b/LICENSE index 8702654f..bb51abac 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,214 @@ -MIT License - -Copyright (c) 2019 Sebastian Schmidt - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + +GNU AFFERO GENERAL PUBLIC LICENSE + +Version 3, 19 November 2007 + +Copyright © 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. +Preamble + +The GNU 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. + + + Copyright (C) + + 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 . + +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 . diff --git a/README.md b/README.md index 363e55a5..cad5f23a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # evalexpr [![Version](https://img.shields.io/crates/v/evalexpr.svg)](https://crates.io/crates/evalexpr) +[![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](https://www.gnu.org/licenses/agpl-3.0) [![Downloads](https://img.shields.io/crates/d/evalexpr.svg)](https://crates.io/crates/evalexpr) [![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) [![Coverage Status](https://coveralls.io/repos/github/ISibboI/evalexpr/badge.svg?branch=main)](https://coveralls.io/github/ISibboI/evalexpr?branch=main) @@ -32,13 +33,13 @@ Then you can use `evalexpr` to **evaluate expressions** like this: ```rust use evalexpr::*; -assert_eq!(eval("1 + 2 + 3"), Ok(Value::from(6))); +assert_eq!(eval("1 + 2 + 3"), Ok(Value::from_int(6))); // `eval` returns a variant of the `Value` enum, // while `eval_[type]` returns the respective type directly. // Both can be used interchangeably. assert_eq!(eval_int("1 + 2 + 3"), Ok(6)); -assert_eq!(eval("1 /* inline comments are supported */ - 2 * 3 // as are end-of-line comments"), Ok(Value::from(-5))); -assert_eq!(eval("1.0 + 2 * 3"), Ok(Value::from(7.0))); +assert_eq!(eval("1 /* inline comments are supported */ - 2 * 3 // as are end-of-line comments"), Ok(Value::from_int(-5))); +assert_eq!(eval("1.0 + 2 * 3"), Ok(Value::from_float(7.0))); assert_eq!(eval("true && 4 > 2"), Ok(Value::from(true))); ``` @@ -47,14 +48,14 @@ You can **chain** expressions and **assign** to variables like this: ```rust use evalexpr::*; -let mut context = HashMapContext::new(); +let mut context = HashMapContext::::new(); // Assign 5 to a like this assert_eq!(eval_empty_with_context_mut("a = 5", &mut context), Ok(EMPTY_VALUE)); // The HashMapContext is type safe, so this will fail now assert_eq!(eval_empty_with_context_mut("a = 5.0", &mut context), - Err(EvalexprError::expected_int(Value::from(5.0)))); + Err(EvalexprError::expected_int(Value::from_float(5.0)))); // We can check which value the context stores for a like this -assert_eq!(context.get_value("a"), Some(&Value::from(5))); +assert_eq!(context.get_value("a"), Some(&Value::from_int(5))); // And use the value in another expression like this assert_eq!(eval_int_with_context_mut("a = a + 2; a", &mut context), Ok(7)); // It is also possible to save a bit of typing by using an operator-assignment operator @@ -66,9 +67,9 @@ And you can use **variables** and **functions** in expressions like this: ```rust use evalexpr::*; -let context = context_map! { - "five" => 5, - "twelve" => 12, +let context: HashMapContext = context_map! { + "five" => int 5, + "twelve" => int 12, "f" => Function::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Int(int / 2)) @@ -102,16 +103,16 @@ You can also **precompile** expressions like this: ```rust use evalexpr::*; -let precompiled = build_operator_tree("a * b - c > 5").unwrap(); // Do proper error handling here +let precompiled = build_operator_tree::("a * b - c > 5").unwrap(); // Do proper error handling here let mut context = context_map! { - "a" => 6, - "b" => 2, - "c" => 3 + "a" => int 6, + "b" => int 2, + "c" => int 3, }.unwrap(); // Do proper error handling here assert_eq!(precompiled.eval_with_context(&context), Ok(Value::from(true))); -context.set_value("c".into(), 8.into()).unwrap(); // Do proper error handling here +context.set_value("c".into(), Value::from_int(8)).unwrap(); // Do proper error handling here assert_eq!(precompiled.eval_with_context(&context), Ok(Value::from(false))); // `Node::eval_with_context` returns a variant of the `Value` enum, // while `Node::eval_[type]_with_context` returns the respective type directly. @@ -184,9 +185,9 @@ Example: ```rust use evalexpr::*; -assert_eq!(eval("1 / 2"), Ok(Value::from(0))); -assert_eq!(eval("1.0 / 2"), Ok(Value::from(0.5))); -assert_eq!(eval("2^2"), Ok(Value::from(4.0))); +assert_eq!(eval("1 / 2"), Ok(Value::from_int(0))); +assert_eq!(eval("1.0 / 2"), Ok(Value::from_float(0.5))); +assert_eq!(eval("2^2"), Ok(Value::from_float(4.0))); ``` #### The Aggregation Operator @@ -200,7 +201,7 @@ Example: use evalexpr::*; assert_eq!(eval("1, \"b\", 3"), - Ok(Value::from(vec![Value::from(1), Value::from("b"), Value::from(3)]))); + Ok(Value::from(vec![Value::from_int(1), Value::from("b"), Value::from_int(3)]))); ``` To create nested tuples, use parentheses: @@ -209,8 +210,8 @@ To create nested tuples, use parentheses: use evalexpr::*; assert_eq!(eval("1, 2, (true, \"b\")"), Ok(Value::from(vec![ - Value::from(1), - Value::from(2), + Value::from_int(1), + Value::from_int(2), Value::from(vec![ Value::from(true), Value::from("b") @@ -229,13 +230,13 @@ That means that if an identifier is assigned a value of a type once, it cannot b ```rust use evalexpr::*; -let mut context = HashMapContext::new(); +let mut context = HashMapContext::::new(); assert_eq!(eval_with_context("a = 5", &context), Err(EvalexprError::ContextNotMutable)); assert_eq!(eval_empty_with_context_mut("a = 5", &mut context), Ok(EMPTY_VALUE)); assert_eq!(eval_empty_with_context_mut("a = 5.0", &mut context), - Err(EvalexprError::expected_int(5.0.into()))); + Err(EvalexprError::expected_int(Value::from_float(5.0)))); assert_eq!(eval_int_with_context("a", &context), Ok(5)); -assert_eq!(context.get_value("a"), Some(5.into()).as_ref()); +assert_eq!(context.get_value("a"), Some(Value::from_int(5)).as_ref()); ``` For each binary operator, there exists an equivalent operator-assignment operator. @@ -260,9 +261,9 @@ Expression chaining is useful together with assignment to create small scripts. ```rust use evalexpr::*; -let mut context = HashMapContext::new(); +let mut context = HashMapContext::::new(); assert_eq!(eval("1;2;3;4;"), Ok(Value::Empty)); -assert_eq!(eval("1;2;3;4"), Ok(4.into())); +assert_eq!(eval("1;2;3;4"), Ok(Value::from_int(4))); // Initialization of variables via script assert_eq!(eval_empty_with_context_mut("hp = 1; max_hp = 5; heal_amount = 3;", &mut context), @@ -290,15 +291,15 @@ assert_eq!(eval("a = 5;"), Ok(Value::from(()))); // The context is not preserved between eval calls assert_eq!(eval("a"), Err(EvalexprError::VariableIdentifierNotFound("a".to_string()))); -let mut context = HashMapContext::new(); +let mut context = HashMapContext::::new(); assert_eq!(eval_with_context_mut("a = 5;", &mut context), Ok(Value::from(()))); // Assignments require mutable contexts assert_eq!(eval_with_context("a = 6", &context), Err(EvalexprError::ContextNotMutable)); // The HashMapContext is type safe assert_eq!(eval_with_context_mut("a = 5.5", &mut context), - Err(EvalexprError::ExpectedInt { actual: Value::from(5.5) })); + Err(EvalexprError::ExpectedInt { actual: Value::from_float(5.5) })); // Reading a variable does not require a mutable context -assert_eq!(eval_with_context("a", &context), Ok(Value::from(5))); +assert_eq!(eval_with_context("a", &context), Ok(Value::from_int(5))); ``` @@ -318,16 +319,16 @@ Take a look at the following example: ```rust use evalexpr::*; -let mut context = HashMapContext::new(); +let mut context = HashMapContext::::new(); // We can set variables in code like this... -context.set_value("a".into(), 5.into()); +context.set_value("a".into(), Value::from_int(5)); // ...and read from them in expressions assert_eq!(eval_int_with_context("a", &context), Ok(5)); // We can write or overwrite variables in expressions... assert_eq!(eval_with_context_mut("a = 10; b = 1.0;", &mut context), Ok(().into())); // ...and read the value in code like this -assert_eq!(context.get_value("a"), Some(&Value::from(10))); -assert_eq!(context.get_value("b"), Some(&Value::from(1.0))); +assert_eq!(context.get_value("a"), Some(&Value::from_int(10))); +assert_eq!(context.get_value("b"), Some(&Value::from_float(1.0))); ``` Contexts are also required for user-defined functions. @@ -336,8 +337,8 @@ Those can be passed one by one with the `set_function` method, but it might be m ```rust use evalexpr::*; -let context = context_map!{ - "f" => Function::new(|args| Ok(Value::from(args.as_int()? + 5))), +let context: HashMapContext = context_map!{ + "f" => Function::new(|args| Ok(Value::from_int(args.as_int()? + 5))), }.unwrap_or_else(|error| panic!("Error creating context: {}", error)); assert_eq!(eval_int_with_context("f 5", &context), Ok(10)); ``` @@ -351,8 +352,8 @@ They can be disabled if needed as follows: ```rust use evalexpr::*; -let mut context = HashMapContext::new(); -assert_eq!(eval_with_context("max(1,3)",&context),Ok(Value::from(3))); +let mut context = HashMapContext::::new(); +assert_eq!(eval_with_context("max(1,3)",&context),Ok(Value::from_int(3))); context.set_builtin_functions_disabled(true).unwrap(); // Do proper error handling here assert_eq!(eval_with_context("max(1,3)",&context),Err(EvalexprError::FunctionIdentifierNotFound(String::from("max")))); ``` @@ -568,7 +569,7 @@ let mut context = context_map!{ // In ron format, strings are surrounded by " let serialized_free = "\"five * five\""; match ron::de::from_str::(serialized_free) { - Ok(free) => assert_eq!(free.eval_with_context(&context), Ok(Value::from(25))), + Ok(free) => assert_eq!(free.eval_with_context(&context), Ok(Value::from_int(25))), Err(error) => { () // Handle error } @@ -580,10 +581,13 @@ With `serde`, expressions can be integrated into arbitrarily complex data. The crate also implements `Serialize` and `Deserialize` for the `HashMapContext`, but note that only the variables get (de)serialized, not the functions. -## License +## Licensing -This crate is primarily distributed under the terms of the MIT license. -See [LICENSE](LICENSE) for details. +This crate is primarily distributed under the terms of the AGPL3 license. +See [LICENSE](/LICENSE) for details. +If you require a different licensing option for your project, contact me at `isibboi at gmail.com`. + +Contributions to this crate are assumed to be licensed under the [MIT License](https://opensource.org/license/mit). diff --git a/benches/benchs.rs b/benches/benchs.rs index 132a12b6..47aacf76 100644 --- a/benches/benchs.rs +++ b/benches/benchs.rs @@ -5,7 +5,7 @@ extern crate rand; extern crate rand_pcg; extern crate test; -use evalexpr::build_operator_tree; +use evalexpr::{build_operator_tree, DefaultNumericTypes}; use rand::{distributions::Uniform, seq::SliceRandom, Rng, SeedableRng}; use rand_pcg::Pcg32; use std::{fmt::Write, hint::black_box}; @@ -68,7 +68,7 @@ fn bench_parse_long_expression_chains(bencher: &mut Bencher) { let mut gen = Pcg32::seed_from_u64(0); let long_expression_chain = generate_expression_chain(BENCHMARK_LEN, &mut gen); - bencher.iter(|| build_operator_tree(&long_expression_chain).unwrap()); + bencher.iter(|| build_operator_tree::(&long_expression_chain).unwrap()); } #[bench] @@ -76,7 +76,7 @@ fn bench_parse_deep_expression_trees(bencher: &mut Bencher) { let mut gen = Pcg32::seed_from_u64(15); let deep_expression_tree = generate_expression(BENCHMARK_LEN, &mut gen); - bencher.iter(|| build_operator_tree(&deep_expression_tree).unwrap()); + bencher.iter(|| build_operator_tree::(&deep_expression_tree).unwrap()); } #[bench] @@ -86,7 +86,7 @@ fn bench_parse_many_small_expressions(bencher: &mut Bencher) { bencher.iter(|| { for expression in &small_expressions { - black_box(build_operator_tree(expression).unwrap()); + black_box(build_operator_tree::(expression).unwrap()); } }); } @@ -94,8 +94,10 @@ fn bench_parse_many_small_expressions(bencher: &mut Bencher) { #[bench] fn bench_evaluate_long_expression_chains(bencher: &mut Bencher) { let mut gen = Pcg32::seed_from_u64(0); - let long_expression_chain = - build_operator_tree(&generate_expression_chain(BENCHMARK_LEN, &mut gen)).unwrap(); + let long_expression_chain = build_operator_tree::( + &generate_expression_chain(BENCHMARK_LEN, &mut gen), + ) + .unwrap(); bencher.iter(|| long_expression_chain.eval().unwrap()); } @@ -104,7 +106,8 @@ fn bench_evaluate_long_expression_chains(bencher: &mut Bencher) { fn bench_evaluate_deep_expression_trees(bencher: &mut Bencher) { let mut gen = Pcg32::seed_from_u64(15); let deep_expression_tree = - build_operator_tree(&generate_expression(BENCHMARK_LEN, &mut gen)).unwrap(); + build_operator_tree::(&generate_expression(BENCHMARK_LEN, &mut gen)) + .unwrap(); bencher.iter(|| deep_expression_tree.eval().unwrap()); } @@ -114,7 +117,7 @@ fn bench_evaluate_many_small_expressions(bencher: &mut Bencher) { let mut gen = Pcg32::seed_from_u64(33); let small_expressions: Vec<_> = generate_small_expressions(BENCHMARK_LEN, &mut gen) .iter() - .map(|expression| build_operator_tree(expression).unwrap()) + .map(|expression| build_operator_tree::(expression).unwrap()) .collect(); bencher.iter(|| { @@ -127,10 +130,9 @@ fn bench_evaluate_many_small_expressions(bencher: &mut Bencher) { #[bench] fn bench_evaluate_large_tuple_expression(bencher: &mut Bencher) { let mut gen = Pcg32::seed_from_u64(44); - let large_tuple_expression = build_operator_tree(&generate_large_tuple_expression( - EXPONENTIAL_TUPLE_ITERATIONS, - &mut gen, - )) + let large_tuple_expression = build_operator_tree::( + &generate_large_tuple_expression(EXPONENTIAL_TUPLE_ITERATIONS, &mut gen), + ) .unwrap(); dbg!(&large_tuple_expression); diff --git a/rust-toolchain.toml b/rust-toolchain.toml index ae217635..0f102b72 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "1.65.0" +channel = "1.81.0" profile = "minimal" components = ["rustfmt", "clippy"] diff --git a/rustfmt.toml b/rustfmt.toml index bca1a3dc..fadf3f56 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,4 +1,4 @@ -edition = "2018" +edition = "2021" reorder_imports=true reorder_modules=true format_strings=true diff --git a/src/context/mod.rs b/src/context/mod.rs index 3306e015..dea9837f 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -4,11 +4,16 @@ //! This crate implements two basic variants, the `EmptyContext`, that returns `None` for each identifier and cannot be manipulated, and the `HashMapContext`, that stores its mappings in hash maps. //! The HashMapContext is type-safe and returns an error if the user tries to assign a value of a different type than before to an identifier. -use std::{collections::HashMap, iter}; +use std::{collections::HashMap, iter, marker::PhantomData}; use crate::{ + error::EvalexprResultValue, function::Function, - value::{value_type::ValueType, Value}, + value::{ + numeric_types::{DefaultNumericTypes, EvalexprNumericTypes}, + value_type::ValueType, + Value, + }, EvalexprError, EvalexprResult, }; @@ -16,25 +21,39 @@ mod predefined; /// An immutable context. pub trait Context { + /// The numeric types used for evaluation. + type NumericTypes: EvalexprNumericTypes; + /// Returns the value that is linked to the given identifier. - fn get_value(&self, identifier: &str) -> Option<&Value>; + fn get_value(&self, identifier: &str) -> Option<&Value>; /// Calls the function that is linked to the given identifier with the given argument. /// If no function with the given identifier is found, this method returns `EvalexprError::FunctionIdentifierNotFound`. - fn call_function(&self, identifier: &str, argument: &Value) -> EvalexprResult; + fn call_function( + &self, + identifier: &str, + argument: &Value, + ) -> EvalexprResultValue; /// Checks if builtin functions are disabled. fn are_builtin_functions_disabled(&self) -> bool; /// Disables builtin functions if `disabled` is `true`, and enables them otherwise. /// If the context does not support enabling or disabling builtin functions, an error is returned. - fn set_builtin_functions_disabled(&mut self, disabled: bool) -> EvalexprResult<()>; + fn set_builtin_functions_disabled( + &mut self, + disabled: bool, + ) -> EvalexprResult<(), Self::NumericTypes>; } /// A context that allows to assign to variables. pub trait ContextWithMutableVariables: Context { /// Sets the variable with the given identifier to the given value. - fn set_value(&mut self, _identifier: String, _value: Value) -> EvalexprResult<()> { + fn set_value( + &mut self, + _identifier: String, + _value: Value, + ) -> EvalexprResult<(), Self::NumericTypes> { Err(EvalexprError::ContextNotMutable) } } @@ -42,17 +61,19 @@ pub trait ContextWithMutableVariables: Context { /// A context that allows to assign to function identifiers. pub trait ContextWithMutableFunctions: Context { /// Sets the function with the given identifier to the given function. - fn set_function(&mut self, _identifier: String, _function: Function) -> EvalexprResult<()> { + fn set_function( + &mut self, + _identifier: String, + _function: Function, + ) -> EvalexprResult<(), Self::NumericTypes> { Err(EvalexprError::ContextNotMutable) } } /// A context that allows to iterate over its variable names with their values. -/// -/// **Note:** this trait will change after GATs are stabilised, because then we can get rid of the lifetime in the trait definition. -pub trait IterateVariablesContext { +pub trait IterateVariablesContext: Context { /// The iterator type for iterating over variable name-value pairs. - type VariableIterator<'a>: Iterator + type VariableIterator<'a>: Iterator)> where Self: 'a; /// The iterator type for iterating over variable names. @@ -78,15 +99,21 @@ pub trait GetFunctionContext: Context { /// A context that returns `None` for each identifier. /// Builtin functions are disabled and cannot be enabled. -#[derive(Debug, Default)] -pub struct EmptyContext; +#[derive(Debug)] +pub struct EmptyContext(PhantomData); + +impl Context for EmptyContext { + type NumericTypes = NumericTypes; -impl Context for EmptyContext { - fn get_value(&self, _identifier: &str) -> Option<&Value> { + fn get_value(&self, _identifier: &str) -> Option<&Value> { None } - fn call_function(&self, identifier: &str, _argument: &Value) -> EvalexprResult { + fn call_function( + &self, + identifier: &str, + _argument: &Value, + ) -> EvalexprResultValue { Err(EvalexprError::FunctionIdentifierNotFound( identifier.to_string(), )) @@ -98,7 +125,10 @@ impl Context for EmptyContext { } /// Builtin functions can't be enabled for `EmptyContext`. - fn set_builtin_functions_disabled(&mut self, disabled: bool) -> EvalexprResult<()> { + fn set_builtin_functions_disabled( + &mut self, + disabled: bool, + ) -> EvalexprResult<(), Self::NumericTypes> { if disabled { Ok(()) } else { @@ -107,9 +137,9 @@ impl Context for EmptyContext { } } -impl IterateVariablesContext for EmptyContext { - type VariableIterator<'a> = iter::Empty<(String, Value)>; - type VariableNameIterator<'a> = iter::Empty; +impl IterateVariablesContext for EmptyContext { + type VariableIterator<'a> = iter::Empty<(String, Value)> where Self: 'a; + type VariableNameIterator<'a> = iter::Empty where Self: 'a; fn iter_variables(&self) -> Self::VariableIterator<'_> { iter::empty() @@ -120,17 +150,31 @@ impl IterateVariablesContext for EmptyContext { } } +impl Default for EmptyContext { + fn default() -> Self { + Self(PhantomData) + } +} + /// A context that returns `None` for each identifier. /// Builtin functions are enabled and cannot be disabled. -#[derive(Debug, Default)] -pub struct EmptyContextWithBuiltinFunctions; +#[derive(Debug)] +pub struct EmptyContextWithBuiltinFunctions(PhantomData); + +impl Context + for EmptyContextWithBuiltinFunctions +{ + type NumericTypes = NumericTypes; -impl Context for EmptyContextWithBuiltinFunctions { - fn get_value(&self, _identifier: &str) -> Option<&Value> { + fn get_value(&self, _identifier: &str) -> Option<&Value> { None } - fn call_function(&self, identifier: &str, _argument: &Value) -> EvalexprResult { + fn call_function( + &self, + identifier: &str, + _argument: &Value, + ) -> EvalexprResultValue { Err(EvalexprError::FunctionIdentifierNotFound( identifier.to_string(), )) @@ -142,7 +186,10 @@ impl Context for EmptyContextWithBuiltinFunctions { } /// Builtin functions can't be disabled for EmptyContextWithBuiltinFunctions. - fn set_builtin_functions_disabled(&mut self, disabled: bool) -> EvalexprResult<()> { + fn set_builtin_functions_disabled( + &mut self, + disabled: bool, + ) -> EvalexprResult<(), Self::NumericTypes> { if disabled { Err(EvalexprError::BuiltinFunctionsCannotBeDisabled) } else { @@ -151,9 +198,11 @@ impl Context for EmptyContextWithBuiltinFunctions { } } -impl IterateVariablesContext for EmptyContextWithBuiltinFunctions { - type VariableIterator<'a> = iter::Empty<(String, Value)>; - type VariableNameIterator<'a> = iter::Empty; +impl IterateVariablesContext + for EmptyContextWithBuiltinFunctions +{ + type VariableIterator<'a> = iter::Empty<(String, Value)> where Self: 'a; + type VariableNameIterator<'a> = iter::Empty where Self:'a; fn iter_variables(&self) -> Self::VariableIterator<'_> { iter::empty() @@ -164,23 +213,29 @@ impl IterateVariablesContext for EmptyContextWithBuiltinFunctions { } } +impl Default for EmptyContextWithBuiltinFunctions { + fn default() -> Self { + Self(PhantomData) + } +} + /// A context that stores its mappings in hash maps. /// /// *Value and function mappings are stored independently, meaning that there can be a function and a value with the same identifier.* /// /// This context is type-safe, meaning that an identifier that is assigned a value of some type once cannot be assigned a value of another type. -#[derive(Clone, Debug, Default)] -#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] -pub struct HashMapContext { - variables: HashMap, - #[cfg_attr(feature = "serde_support", serde(skip))] - functions: HashMap, +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct HashMapContext { + variables: HashMap>, + #[cfg_attr(feature = "serde", serde(skip))] + functions: HashMap>, /// True if builtin functions are disabled. without_builtin_functions: bool, } -impl HashMapContext { +impl HashMapContext { /// Constructs a `HashMapContext` with no mappings. pub fn new() -> Self { Default::default() @@ -194,7 +249,7 @@ impl HashMapContext { /// ```rust /// # use evalexpr::*; /// - /// let mut context = HashMapContext::new(); + /// let mut context = HashMapContext::::new(); /// context.set_value("abc".into(), "def".into()).unwrap(); /// assert_eq!(context.get_value("abc"), Some(&("def".into()))); /// context.clear_variables(); @@ -218,7 +273,7 @@ impl HashMapContext { /// ```rust /// # use evalexpr::*; /// - /// let mut context = HashMapContext::new(); + /// let mut context = HashMapContext::::new(); /// context.set_value("abc".into(), "def".into()).unwrap(); /// assert_eq!(context.get_value("abc"), Some(&("def".into()))); /// context.clear(); @@ -230,12 +285,18 @@ impl HashMapContext { } } -impl Context for HashMapContext { - fn get_value(&self, identifier: &str) -> Option<&Value> { +impl Context for HashMapContext { + type NumericTypes = NumericTypes; + + fn get_value(&self, identifier: &str) -> Option<&Value> { self.variables.get(identifier) } - fn call_function(&self, identifier: &str, argument: &Value) -> EvalexprResult { + fn call_function( + &self, + identifier: &str, + argument: &Value, + ) -> EvalexprResultValue { if let Some(function) = self.functions.get(identifier) { function.call(argument) } else { @@ -249,14 +310,23 @@ impl Context for HashMapContext { self.without_builtin_functions } - fn set_builtin_functions_disabled(&mut self, disabled: bool) -> EvalexprResult<()> { + fn set_builtin_functions_disabled( + &mut self, + disabled: bool, + ) -> EvalexprResult<(), NumericTypes> { self.without_builtin_functions = disabled; Ok(()) } } -impl ContextWithMutableVariables for HashMapContext { - fn set_value(&mut self, identifier: String, value: Value) -> EvalexprResult<()> { +impl ContextWithMutableVariables + for HashMapContext +{ + fn set_value( + &mut self, + identifier: String, + value: Value, + ) -> EvalexprResult<(), NumericTypes> { if let Some(existing_value) = self.variables.get_mut(&identifier) { if ValueType::from(&existing_value) == ValueType::from(&value) { *existing_value = value; @@ -272,20 +342,26 @@ impl ContextWithMutableVariables for HashMapContext { } } -impl ContextWithMutableFunctions for HashMapContext { - fn set_function(&mut self, identifier: String, function: Function) -> EvalexprResult<()> { +impl ContextWithMutableFunctions + for HashMapContext +{ + fn set_function( + &mut self, + identifier: String, + function: Function, + ) -> EvalexprResult<(), Self::NumericTypes> { self.functions.insert(identifier, function); Ok(()) } } -impl IterateVariablesContext for HashMapContext { +impl IterateVariablesContext for HashMapContext { type VariableIterator<'a> = std::iter::Map< - std::collections::hash_map::Iter<'a, String, Value>, - fn((&String, &Value)) -> (String, Value), - >; + std::collections::hash_map::Iter<'a, String, Value>, + fn((&String, &Value)) -> (String, Value), + > where Self: 'a; type VariableNameIterator<'a> = - std::iter::Cloned>; + std::iter::Cloned>> where Self: 'a; fn iter_variables(&self) -> Self::VariableIterator<'_> { self.variables @@ -298,6 +374,16 @@ impl IterateVariablesContext for HashMapContext { } } +impl Default for HashMapContext { + fn default() -> Self { + Self { + variables: Default::default(), + functions: Default::default(), + without_builtin_functions: false, + } + } +} + /// This macro provides a convenient syntax for creating a static context. /// /// # Examples @@ -305,18 +391,22 @@ impl IterateVariablesContext for HashMapContext { /// ```rust /// use evalexpr::*; /// -/// let ctx = evalexpr::context_map! { -/// "x" => 8, -/// "f" => Function::new(|_| Ok(42.into())) +/// let ctx: HashMapContext = context_map! { +/// "x" => int 8, +/// "f" => Function::new(|_| Ok(Value::from_int(42))) /// }.unwrap(); // Do proper error handling here /// -/// assert_eq!(eval_with_context("x + f()", &ctx), Ok(50.into())); +/// assert_eq!(eval_with_context("x + f()", &ctx), Ok(Value::from_int(50))); /// ``` #[macro_export] macro_rules! context_map { // Termination (allow missing comma at the end of the argument list) ( ($ctx:expr) $k:expr => Function::new($($v:tt)*) ) => { $crate::context_map!(($ctx) $k => Function::new($($v)*),) }; + ( ($ctx:expr) $k:expr => int $v:expr ) => + { $crate::context_map!(($ctx) $k => int $v,) }; + ( ($ctx:expr) $k:expr => float $v:expr ) => + { $crate::context_map!(($ctx) $k => float $v,) }; ( ($ctx:expr) $k:expr => $v:expr ) => { $crate::context_map!(($ctx) $k => $v,) }; // Termination @@ -327,6 +417,16 @@ macro_rules! context_map { $crate::ContextWithMutableFunctions::set_function($ctx, $k.into(), $crate::Function::new($($v)*)) .and($crate::context_map!(($ctx) $($tt)*)) }}; + // add an integer value, and chain the eventual error with the ones in the next values + ( ($ctx:expr) $k:expr => int $v:expr , $($tt:tt)*) => {{ + $crate::ContextWithMutableVariables::set_value($ctx, $k.into(), Value::from_int($v.into())) + .and($crate::context_map!(($ctx) $($tt)*)) + }}; + // add a float value, and chain the eventual error with the ones in the next values + ( ($ctx:expr) $k:expr => float $v:expr , $($tt:tt)*) => {{ + $crate::ContextWithMutableVariables::set_value($ctx, $k.into(), Value::from_float($v.into())) + .and($crate::context_map!(($ctx) $($tt)*)) + }}; // add a value, and chain the eventual error with the ones in the next values ( ($ctx:expr) $k:expr => $v:expr , $($tt:tt)*) => {{ $crate::ContextWithMutableVariables::set_value($ctx, $k.into(), $v.into()) diff --git a/src/error/display.rs b/src/error/display.rs index faa218a1..d4626017 100644 --- a/src/error/display.rs +++ b/src/error/display.rs @@ -1,8 +1,8 @@ use std::fmt; -use crate::EvalexprError; +use crate::{value::numeric_types::EvalexprNumericTypes, EvalexprError}; -impl fmt::Display for EvalexprError { +impl fmt::Display for EvalexprError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { use crate::EvalexprError::*; match self { @@ -139,6 +139,17 @@ impl fmt::Display for EvalexprError { }, IllegalEscapeSequence(string) => write!(f, "Illegal escape sequence: {}", string), OutOfBoundsAccess => write!(f, "Tried to access a tuple or string at an invalid index"), + IntFromUsize { usize_int } => write!( + f, + "The usize {} does not fit into the chosen integer type", + usize_int + ), + IntIntoUsize { int } => write!( + f, + "The int {} does not fit into an usize on this platform", + int + ), + RandNotEnabled => write!(f, "The feature 'rand' must be enabled to use randomness"), CustomMessage(message) => write!(f, "Error: {}", message), } } diff --git a/src/error/mod.rs b/src/error/mod.rs index 7de0651d..7b3cf6b2 100644 --- a/src/error/mod.rs +++ b/src/error/mod.rs @@ -7,6 +7,7 @@ use std::ops::RangeInclusive; +use crate::value::numeric_types::{DefaultNumericTypes, EvalexprNumericTypes}; use crate::{token::PartialToken, value::value_type::ValueType}; use crate::{operator::Operator, value::Value}; @@ -18,7 +19,7 @@ mod display; /// Errors used in this crate. #[derive(Debug, Clone, PartialEq)] #[non_exhaustive] -pub enum EvalexprError { +pub enum EvalexprError { /// An operator was called with a wrong amount of arguments. WrongOperatorArgumentAmount { /// The expected amount of arguments. @@ -38,45 +39,45 @@ pub enum EvalexprError { /// A string value was expected. ExpectedString { /// The actual value. - actual: Value, + actual: Value, }, /// An integer value was expected. ExpectedInt { /// The actual value. - actual: Value, + actual: Value, }, /// A float value was expected. ExpectedFloat { /// The actual value. - actual: Value, + actual: Value, }, /// A numeric value was expected. /// Numeric values are the variants `Value::Int` and `Value::Float`. ExpectedNumber { /// The actual value. - actual: Value, + actual: Value, }, /// A numeric or string value was expected. /// Numeric values are the variants `Value::Int` and `Value::Float`. ExpectedNumberOrString { /// The actual value. - actual: Value, + actual: Value, }, /// A boolean value was expected. ExpectedBoolean { /// The actual value. - actual: Value, + actual: Value, }, /// A tuple value was expected. ExpectedTuple { /// The actual value. - actual: Value, + actual: Value, }, /// A tuple value of a certain length was expected. @@ -84,7 +85,7 @@ pub enum EvalexprError { /// The expected length. expected_length: usize, /// The actual value. - actual: Value, + actual: Value, }, /// A tuple value of a certain length range was expected. @@ -92,13 +93,13 @@ pub enum EvalexprError { /// The expected length range. expected_length: RangeInclusive, /// The actual value. - actual: Value, + actual: Value, }, /// An empty value was expected. ExpectedEmpty { /// The actual value. - actual: Value, + actual: Value, }, /// Tried to append a child to a leaf node. @@ -122,13 +123,13 @@ pub enum EvalexprError { /// The expected types. expected: Vec, /// The actual value. - actual: Value, + actual: Value, }, /// An operator is used with a wrong combination of types. WrongTypeCombination { /// The operator that whose evaluation caused the error. - operator: Operator, + operator: Operator, /// The types that were used in the operator causing it to fail. actual: Vec, }, @@ -151,55 +152,55 @@ pub enum EvalexprError { /// It is not a token, but it is part of the string representation of some tokens. UnmatchedPartialToken { /// The unmatched partial token. - first: PartialToken, + first: PartialToken, /// The token that follows the unmatched partial token and that cannot be matched to the partial token, or `None`, if `first` is the last partial token in the stream. - second: Option, + second: Option>, }, /// An addition operation performed by Rust failed. AdditionError { /// The first argument of the addition. - augend: Value, + augend: Value, /// The second argument of the addition. - addend: Value, + addend: Value, }, /// A subtraction operation performed by Rust failed. SubtractionError { /// The first argument of the subtraction. - minuend: Value, + minuend: Value, /// The second argument of the subtraction. - subtrahend: Value, + subtrahend: Value, }, /// A negation operation performed by Rust failed. NegationError { /// The argument of the negation. - argument: Value, + argument: Value, }, /// A multiplication operation performed by Rust failed. MultiplicationError { /// The first argument of the multiplication. - multiplicand: Value, + multiplicand: Value, /// The second argument of the multiplication. - multiplier: Value, + multiplier: Value, }, /// A division operation performed by Rust failed. DivisionError { /// The first argument of the division. - dividend: Value, + dividend: Value, /// The second argument of the division. - divisor: Value, + divisor: Value, }, /// A modulation operation performed by Rust failed. ModulationError { /// The first argument of the modulation. - dividend: Value, + dividend: Value, /// The second argument of the modulation. - divisor: Value, + divisor: Value, }, /// A regular expression could not be parsed @@ -225,11 +226,26 @@ pub enum EvalexprError { /// Out of bounds sequence access. OutOfBoundsAccess, + /// A `usize` was attempted to be converted to an `int`, but it was out of range. + IntFromUsize { + /// The `usize` that was attempted to be converted. + usize_int: usize, + }, + + /// An `int` was attempted to be converted to a `usize`, but it was out of range. + IntIntoUsize { + /// The `int` that was attempted to be converted. + int: NumericTypes::Int, + }, + + /// The feature `rand` is not enabled, but required for the used function. + RandNotEnabled, + /// A custom error explained by its message. CustomMessage(String), } -impl EvalexprError { +impl EvalexprError { /// Construct a `WrongOperatorArgumentAmount` error. pub fn wrong_operator_argument_amount(actual: usize, expected: usize) -> Self { EvalexprError::WrongOperatorArgumentAmount { actual, expected } @@ -252,52 +268,55 @@ impl EvalexprError { } /// Constructs `EvalexprError::TypeError{actual, expected}`. - pub fn type_error(actual: Value, expected: Vec) -> Self { + pub fn type_error(actual: Value, expected: Vec) -> Self { EvalexprError::TypeError { actual, expected } } /// Constructs `EvalexprError::WrongTypeCombination{operator, actual}`. - pub fn wrong_type_combination(operator: Operator, actual: Vec) -> Self { + pub fn wrong_type_combination( + operator: Operator, + actual: Vec, + ) -> Self { EvalexprError::WrongTypeCombination { operator, actual } } /// Constructs `EvalexprError::ExpectedString{actual}`. - pub fn expected_string(actual: Value) -> Self { + pub fn expected_string(actual: Value) -> Self { EvalexprError::ExpectedString { actual } } /// Constructs `EvalexprError::ExpectedInt{actual}`. - pub fn expected_int(actual: Value) -> Self { + pub fn expected_int(actual: Value) -> Self { EvalexprError::ExpectedInt { actual } } /// Constructs `EvalexprError::ExpectedFloat{actual}`. - pub fn expected_float(actual: Value) -> Self { + pub fn expected_float(actual: Value) -> Self { EvalexprError::ExpectedFloat { actual } } /// Constructs `EvalexprError::ExpectedNumber{actual}`. - pub fn expected_number(actual: Value) -> Self { + pub fn expected_number(actual: Value) -> Self { EvalexprError::ExpectedNumber { actual } } /// Constructs `EvalexprError::ExpectedNumberOrString{actual}`. - pub fn expected_number_or_string(actual: Value) -> Self { + pub fn expected_number_or_string(actual: Value) -> Self { EvalexprError::ExpectedNumberOrString { actual } } /// Constructs `EvalexprError::ExpectedBoolean{actual}`. - pub fn expected_boolean(actual: Value) -> Self { + pub fn expected_boolean(actual: Value) -> Self { EvalexprError::ExpectedBoolean { actual } } /// Constructs `EvalexprError::ExpectedTuple{actual}`. - pub fn expected_tuple(actual: Value) -> Self { + pub fn expected_tuple(actual: Value) -> Self { EvalexprError::ExpectedTuple { actual } } /// Constructs `EvalexprError::ExpectedFixedLenTuple{expected_len, actual}`. - pub fn expected_fixed_len_tuple(expected_len: usize, actual: Value) -> Self { + pub fn expected_fixed_len_tuple(expected_len: usize, actual: Value) -> Self { EvalexprError::ExpectedFixedLengthTuple { expected_length: expected_len, actual, @@ -305,7 +324,10 @@ impl EvalexprError { } /// Constructs `EvalexprError::ExpectedFixedLenTuple{expected_len, actual}`. - pub fn expected_ranged_len_tuple(expected_len: RangeInclusive, actual: Value) -> Self { + pub fn expected_ranged_len_tuple( + expected_len: RangeInclusive, + actual: Value, + ) -> Self { EvalexprError::ExpectedRangedLengthTuple { expected_length: expected_len, actual, @@ -313,12 +335,15 @@ impl EvalexprError { } /// Constructs `EvalexprError::ExpectedEmpty{actual}`. - pub fn expected_empty(actual: Value) -> Self { + pub fn expected_empty(actual: Value) -> Self { EvalexprError::ExpectedEmpty { actual } } /// Constructs an error that expresses that the type of `expected` was expected, but `actual` was found. - pub(crate) fn expected_type(expected: &Value, actual: Value) -> Self { + pub(crate) fn expected_type( + expected: &Value, + actual: Value, + ) -> Self { match ValueType::from(expected) { ValueType::String => Self::expected_string(actual), ValueType::Int => Self::expected_int(actual), @@ -330,39 +355,51 @@ impl EvalexprError { } pub(crate) fn unmatched_partial_token( - first: PartialToken, - second: Option, + first: PartialToken, + second: Option>, ) -> Self { EvalexprError::UnmatchedPartialToken { first, second } } - pub(crate) fn addition_error(augend: Value, addend: Value) -> Self { + pub(crate) fn addition_error(augend: Value, addend: Value) -> Self { EvalexprError::AdditionError { augend, addend } } - pub(crate) fn subtraction_error(minuend: Value, subtrahend: Value) -> Self { + pub(crate) fn subtraction_error( + minuend: Value, + subtrahend: Value, + ) -> Self { EvalexprError::SubtractionError { minuend, subtrahend, } } - pub(crate) fn negation_error(argument: Value) -> Self { + pub(crate) fn negation_error(argument: Value) -> Self { EvalexprError::NegationError { argument } } - pub(crate) fn multiplication_error(multiplicand: Value, multiplier: Value) -> Self { + pub(crate) fn multiplication_error( + multiplicand: Value, + multiplier: Value, + ) -> Self { EvalexprError::MultiplicationError { multiplicand, multiplier, } } - pub(crate) fn division_error(dividend: Value, divisor: Value) -> Self { + pub(crate) fn division_error( + dividend: Value, + divisor: Value, + ) -> Self { EvalexprError::DivisionError { dividend, divisor } } - pub(crate) fn modulation_error(dividend: Value, divisor: Value) -> Self { + pub(crate) fn modulation_error( + dividend: Value, + divisor: Value, + ) -> Self { EvalexprError::ModulationError { dividend, divisor } } @@ -373,10 +410,10 @@ impl EvalexprError { } /// Returns `Ok(())` if the actual and expected parameters are equal, and `Err(Error::WrongOperatorArgumentAmount)` otherwise. -pub(crate) fn expect_operator_argument_amount( +pub(crate) fn expect_operator_argument_amount( actual: usize, expected: usize, -) -> EvalexprResult<()> { +) -> EvalexprResult<(), NumericTypes> { if actual == expected { Ok(()) } else { @@ -387,7 +424,10 @@ pub(crate) fn expect_operator_argument_amount( } /// Returns `Ok(())` if the actual and expected parameters are equal, and `Err(Error::WrongFunctionArgumentAmount)` otherwise. -pub fn expect_function_argument_amount(actual: usize, expected: usize) -> EvalexprResult<()> { +pub fn expect_function_argument_amount( + actual: usize, + expected: usize, +) -> EvalexprResult<(), NumericTypes> { if actual == expected { Ok(()) } else { @@ -398,46 +438,68 @@ pub fn expect_function_argument_amount(actual: usize, expected: usize) -> Evalex } /// Returns `Ok(())` if the given value is a string or a numeric -pub fn expect_number_or_string(actual: &Value) -> EvalexprResult<()> { +pub fn expect_number_or_string( + actual: &Value, +) -> EvalexprResult<(), NumericTypes> { match actual { Value::String(_) | Value::Float(_) | Value::Int(_) => Ok(()), _ => Err(EvalexprError::expected_number_or_string(actual.clone())), } } -impl std::error::Error for EvalexprError {} +impl std::error::Error for EvalexprError {} /// Standard result type used by this crate. -pub type EvalexprResult = Result; +pub type EvalexprResult = + Result>; + +/// Standard result type for [`Value`]s used by this crate. +pub type EvalexprResultValue = + EvalexprResult, NumericTypes>; #[cfg(test)] mod tests { - use crate::{EvalexprError, Value, ValueType}; + use crate::{value::numeric_types::DefaultNumericTypes, EvalexprError, Value, ValueType}; /// Tests whose only use is to bring test coverage of trivial lines up, like trivial constructors. #[test] fn trivial_coverage_tests() { assert_eq!( - EvalexprError::type_error(Value::Int(3), vec![ValueType::String]), + EvalexprError::type_error( + Value::::Int(3), + vec![ValueType::String] + ), EvalexprError::TypeError { actual: Value::Int(3), expected: vec![ValueType::String] } ); assert_eq!( - EvalexprError::expected_type(&Value::String("abc".to_string()), Value::Empty), + EvalexprError::expected_type( + &Value::::String("abc".to_string()), + Value::Empty + ), EvalexprError::expected_string(Value::Empty) ); assert_eq!( - EvalexprError::expected_type(&Value::Boolean(false), Value::Empty), + EvalexprError::expected_type( + &Value::::Boolean(false), + Value::Empty + ), EvalexprError::expected_boolean(Value::Empty) ); assert_eq!( - EvalexprError::expected_type(&Value::Tuple(vec![]), Value::Empty), + EvalexprError::expected_type( + &Value::::Tuple(vec![]), + Value::Empty + ), EvalexprError::expected_tuple(Value::Empty) ); assert_eq!( - EvalexprError::expected_type(&Value::Empty, Value::String("abc".to_string())), + EvalexprError::expected_type( + &Value::::Empty, + Value::String("abc".to_string()) + ), EvalexprError::expected_empty(Value::String("abc".to_string())) ); } diff --git a/src/feature_serde/mod.rs b/src/feature_serde/mod.rs index ee2f85f3..88a5a7c2 100644 --- a/src/feature_serde/mod.rs +++ b/src/feature_serde/mod.rs @@ -1,20 +1,20 @@ -use crate::{interface::build_operator_tree, Node}; +use crate::{interface::build_operator_tree, EvalexprNumericTypes, Node}; use serde::{de, Deserialize, Deserializer}; -use std::fmt; +use std::{fmt, marker::PhantomData}; -impl<'de> Deserialize<'de> for Node { +impl<'de, NumericTypes: EvalexprNumericTypes> Deserialize<'de> for Node { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - deserializer.deserialize_str(NodeVisitor) + deserializer.deserialize_str(NodeVisitor(PhantomData)) } } -struct NodeVisitor; +struct NodeVisitor(PhantomData); -impl de::Visitor<'_> for NodeVisitor { - type Value = Node; +impl de::Visitor<'_> for NodeVisitor { + type Value = Node; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( diff --git a/src/function/builtin.rs b/src/function/builtin.rs index 9aa6f1ac..aec8a8e9 100644 --- a/src/function/builtin.rs +++ b/src/function/builtin.rs @@ -1,54 +1,55 @@ -#[cfg(feature = "regex_support")] +#[cfg(feature = "regex")] use regex::Regex; use crate::{ - value::{FloatType, IntType}, + value::numeric_types::{EvalexprFloat, EvalexprInt, EvalexprNumericTypes}, EvalexprError, Function, Value, ValueType, }; -use std::{ - convert::TryFrom, - ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr}, -}; macro_rules! simple_math { ($func:ident) => { - Some(Function::new(|argument| { + Some(Function::new(|argument: &Value| { let num = argument.as_number()?; Ok(Value::Float(num.$func())) })) }; ($func:ident, 2) => { - Some(Function::new(|argument| { + Some(Function::new(|argument: &Value| { let tuple = argument.as_fixed_len_tuple(2)?; let (a, b) = (tuple[0].as_number()?, tuple[1].as_number()?); - Ok(Value::Float(a.$func(b))) + Ok(Value::Float(a.$func(&b))) })) }; } -fn float_is(func: fn(FloatType) -> bool) -> Option { - Some(Function::new(move |argument| { - Ok(func(argument.as_number()?).into()) +fn float_is( + func: fn(&NumericTypes::Float) -> bool, +) -> Option> { + Some(Function::new(move |argument: &Value| { + Ok(func(&argument.as_number()?).into()) })) } macro_rules! int_function { ($func:ident) => { Some(Function::new(|argument| { - let int = argument.as_int()?; + let int: NumericTypes::Int = argument.as_int()?; Ok(Value::Int(int.$func())) })) }; ($func:ident, 2) => { Some(Function::new(|argument| { let tuple = argument.as_fixed_len_tuple(2)?; - let (a, b) = (tuple[0].as_int()?, tuple[1].as_int()?); - Ok(Value::Int(a.$func(b))) + let (a, b): (NumericTypes::Int, NumericTypes::Int) = + (tuple[0].as_int()?, tuple[1].as_int()?); + Ok(Value::Int(a.$func(&b))) })) }; } -pub fn builtin_function(identifier: &str) -> Option { +pub fn builtin_function( + identifier: &str, +) -> Option> { match identifier { // Log "math::ln" => simple_math!(ln), @@ -59,7 +60,7 @@ pub fn builtin_function(identifier: &str) -> Option { "math::exp" => simple_math!(exp), "math::exp2" => simple_math!(exp2), // Pow - "math::pow" => simple_math!(powf, 2), + "math::pow" => simple_math!(pow, 2), // Cos "math::cos" => simple_math!(cos), "math::acos" => simple_math!(acos), @@ -86,14 +87,18 @@ pub fn builtin_function(identifier: &str) -> Option { "round" => simple_math!(round), "ceil" => simple_math!(ceil), // Float special values - "math::is_nan" => float_is(FloatType::is_nan), - "math::is_finite" => float_is(FloatType::is_finite), - "math::is_infinite" => float_is(FloatType::is_infinite), - "math::is_normal" => float_is(FloatType::is_normal), - // Absolute + "math::is_nan" => float_is(NumericTypes::Float::is_nan), + "math::is_finite" => float_is(NumericTypes::Float::is_finite), + "math::is_infinite" => float_is(NumericTypes::Float::is_infinite), + "math::is_normal" => float_is(NumericTypes::Float::is_normal), + // Absolute value "math::abs" => Some(Function::new(|argument| match argument { - Value::Float(num) => Ok(Value::Float(num.abs())), - Value::Int(num) => Ok(Value::Int(num.abs())), + Value::Float(num) => Ok(Value::Float( + ::Float::abs(num), + )), + Value::Int(num) => Ok(Value::Int( + ::Int::abs(num)?, + )), _ => Err(EvalexprError::expected_number(argument.clone())), })), // Other @@ -110,13 +115,13 @@ pub fn builtin_function(identifier: &str) -> Option { })), "min" => Some(Function::new(|argument| { let arguments = argument.as_tuple()?; - let mut min_int = IntType::MAX; - let mut min_float: FloatType = 1.0 / 0.0; + let mut min_int = NumericTypes::Int::MAX; + let mut min_float = NumericTypes::Float::MAX; debug_assert!(min_float.is_infinite()); for argument in arguments { if let Value::Float(float) = argument { - min_float = min_float.min(float); + min_float = min_float.min(&float); } else if let Value::Int(int) = argument { min_int = min_int.min(int); } else { @@ -124,7 +129,7 @@ pub fn builtin_function(identifier: &str) -> Option { } } - if (min_int as FloatType) < min_float { + if (NumericTypes::int_as_float(&min_int)) < min_float { Ok(Value::Int(min_int)) } else { Ok(Value::Float(min_float)) @@ -132,13 +137,13 @@ pub fn builtin_function(identifier: &str) -> Option { })), "max" => Some(Function::new(|argument| { let arguments = argument.as_tuple()?; - let mut max_int = IntType::MIN; - let mut max_float: FloatType = -1.0 / 0.0; + let mut max_int = NumericTypes::Int::MIN; + let mut max_float = NumericTypes::Float::MIN; debug_assert!(max_float.is_infinite()); for argument in arguments { if let Value::Float(float) = argument { - max_float = max_float.max(float); + max_float = max_float.max(&float); } else if let Value::Int(int) = argument { max_int = max_int.max(int); } else { @@ -146,7 +151,7 @@ pub fn builtin_function(identifier: &str) -> Option { } } - if (max_int as FloatType) > max_float { + if (NumericTypes::int_as_float(&max_int)) > max_float { Ok(Value::Int(max_int)) } else { Ok(Value::Float(max_float)) @@ -213,9 +218,9 @@ pub fn builtin_function(identifier: &str) -> Option { })), "len" => Some(Function::new(|argument| { if let Ok(subject) = argument.as_string() { - Ok(Value::from(subject.len() as IntType)) + Ok(Value::Int(NumericTypes::Int::from_usize(subject.len())?)) } else if let Ok(subject) = argument.as_tuple() { - Ok(Value::from(subject.len() as IntType)) + Ok(Value::Int(NumericTypes::Int::from_usize(subject.len())?)) } else { Err(EvalexprError::type_error( argument.clone(), @@ -224,7 +229,7 @@ pub fn builtin_function(identifier: &str) -> Option { } })), // String functions - #[cfg(feature = "regex_support")] + #[cfg(feature = "regex")] "str::regex_matches" => Some(Function::new(|argument| { let arguments = argument.as_fixed_len_tuple(2)?; @@ -238,7 +243,7 @@ pub fn builtin_function(identifier: &str) -> Option { )), } })), - #[cfg(feature = "regex_support")] + #[cfg(feature = "regex")] "str::regex_replace" => Some(Function::new(|argument| { let arguments = argument.as_fixed_len_tuple(3)?; @@ -273,10 +278,14 @@ pub fn builtin_function(identifier: &str) -> Option { "str::substring" => Some(Function::new(|argument| { let args = argument.as_ranged_len_tuple(2..=3)?; let subject = args[0].as_string()?; - let start = args[1].as_int()?; - let start = usize::try_from(start).map_err(|_| EvalexprError::OutOfBoundsAccess)?; + let start: NumericTypes::Int = args[1].as_int()?; + let start = start + .into_usize() + .map_err(|_| EvalexprError::OutOfBoundsAccess)?; let end = if let Some(end) = args.get(2) { - usize::try_from(end.as_int()?).map_err(|_| EvalexprError::OutOfBoundsAccess)? + let end: NumericTypes::Int = end.as_int()?; + end.into_usize() + .map_err(|_| EvalexprError::OutOfBoundsAccess)? } else { subject.len() }; @@ -288,15 +297,15 @@ pub fn builtin_function(identifier: &str) -> Option { #[cfg(feature = "rand")] "random" => Some(Function::new(|argument| { argument.as_empty()?; - Ok(Value::Float(rand::random())) + Ok(Value::Float(NumericTypes::Float::random()?)) })), // Bitwise operators "bitand" => int_function!(bitand, 2), "bitor" => int_function!(bitor, 2), "bitxor" => int_function!(bitxor, 2), - "bitnot" => int_function!(not), - "shl" => int_function!(shl, 2), - "shr" => int_function!(shr, 2), + "bitnot" => int_function!(bitnot), + "shl" => int_function!(bit_shift_left, 2), + "shr" => int_function!(bit_shift_right, 2), _ => None, } } diff --git a/src/function/mod.rs b/src/function/mod.rs index c590107c..e61fde18 100644 --- a/src/function/mod.rs +++ b/src/function/mod.rs @@ -1,25 +1,31 @@ use std::fmt; -use crate::{error::EvalexprResult, value::Value}; +use crate::{ + error::EvalexprResultValue, + value::{ + numeric_types::{DefaultNumericTypes, EvalexprNumericTypes}, + Value, + }, +}; pub(crate) mod builtin; /// A helper trait to enable cloning through `Fn` trait objects. -trait ClonableFn +trait ClonableFn where - Self: Fn(&Value) -> EvalexprResult, + Self: Fn(&Value) -> EvalexprResultValue, Self: Send + Sync + 'static, { - fn dyn_clone(&self) -> Box; + fn dyn_clone(&self) -> Box>; } -impl ClonableFn for F +impl ClonableFn for F where - F: Fn(&Value) -> EvalexprResult, + F: Fn(&Value) -> EvalexprResultValue, F: Send + Sync + 'static, F: Clone, { - fn dyn_clone(&self) -> Box { + fn dyn_clone(&self) -> Box> { Box::new(self.clone()) as _ } } @@ -32,17 +38,17 @@ where /// ```rust /// use evalexpr::*; /// -/// let mut context = HashMapContext::new(); +/// let mut context = HashMapContext::::new(); /// context.set_function("id".into(), Function::new(|argument| { /// Ok(argument.clone()) /// })).unwrap(); // Do proper error handling here -/// assert_eq!(eval_with_context("id(4)", &context), Ok(Value::from(4))); +/// assert_eq!(eval_with_context("id(4)", &context), Ok(Value::from_int(4))); /// ``` -pub struct Function { - function: Box, +pub struct Function { + function: Box>, } -impl Clone for Function { +impl Clone for Function { fn clone(&self) -> Self { Self { function: self.function.dyn_clone(), @@ -50,13 +56,13 @@ impl Clone for Function { } } -impl Function { +impl Function { /// Creates a user-defined function. /// /// The `function` is boxed for storage. pub fn new(function: F) -> Self where - F: Fn(&Value) -> EvalexprResult, + F: Fn(&Value) -> EvalexprResultValue, F: Send + Sync + 'static, F: Clone, { @@ -65,12 +71,12 @@ impl Function { } } - pub(crate) fn call(&self, argument: &Value) -> EvalexprResult { + pub(crate) fn call(&self, argument: &Value) -> EvalexprResultValue { (self.function)(argument) } } -impl fmt::Debug for Function { +impl fmt::Debug for Function { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Function {{ [...] }}") } @@ -82,4 +88,4 @@ impl fmt::Debug for Function { #[doc(hidden)] trait IsSendAndSync: Send + Sync {} -impl IsSendAndSync for Function {} +impl IsSendAndSync for Function {} diff --git a/src/interface/mod.rs b/src/interface/mod.rs index 332b704b..0d3ea003 100644 --- a/src/interface/mod.rs +++ b/src/interface/mod.rs @@ -1,6 +1,12 @@ use crate::{ - token, tree, value::TupleType, Context, ContextWithMutableVariables, EmptyType, EvalexprError, - EvalexprResult, FloatType, HashMapContext, IntType, Node, Value, EMPTY_VALUE, + error::EvalexprResultValue, + token, tree, + value::{ + numeric_types::{DefaultNumericTypes, EvalexprNumericTypes}, + TupleType, + }, + Context, ContextWithMutableVariables, EmptyType, EvalexprError, EvalexprResult, HashMapContext, + Node, Value, EMPTY_VALUE, }; /// Evaluate the given expression string. @@ -10,12 +16,12 @@ use crate::{ /// ```rust /// use evalexpr::*; /// -/// assert_eq!(eval("1 + 2 + 3"), Ok(Value::from(6))); +/// assert_eq!(eval("1 + 2 + 3"), Ok(Value::from_int(6))); /// ``` /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval(string: &str) -> EvalexprResult { - eval_with_context_mut(string, &mut HashMapContext::new()) +pub fn eval(string: &str) -> EvalexprResultValue { + eval_with_context_mut(string, &mut HashMapContext::::new()) } /// Evaluate the given expression string with the given context. @@ -25,15 +31,18 @@ pub fn eval(string: &str) -> EvalexprResult { /// ```rust /// use evalexpr::*; /// -/// let mut context = HashMapContext::new(); -/// context.set_value("one".into(), 1.into()).unwrap(); // Do proper error handling here -/// context.set_value("two".into(), 2.into()).unwrap(); // Do proper error handling here -/// context.set_value("three".into(), 3.into()).unwrap(); // Do proper error handling here -/// assert_eq!(eval_with_context("one + two + three", &context), Ok(Value::from(6))); +/// let mut context = HashMapContext::::new(); +/// context.set_value("one".into(), Value::from_int(1)).unwrap(); // Do proper error handling here +/// context.set_value("two".into(), Value::from_int(2)).unwrap(); // Do proper error handling here +/// context.set_value("three".into(), Value::from_int(3)).unwrap(); // Do proper error handling here +/// assert_eq!(eval_with_context("one + two + three", &context), Ok(Value::from_int(6))); /// ``` /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_with_context(string: &str, context: &C) -> EvalexprResult { +pub fn eval_with_context( + string: &str, + context: &C, +) -> EvalexprResultValue { tree::tokens_to_operator_tree(token::tokenize(string)?)?.eval_with_context(context) } @@ -44,18 +53,18 @@ pub fn eval_with_context(string: &str, context: &C) -> EvalexprResul /// ```rust /// use evalexpr::*; /// -/// let mut context = HashMapContext::new(); -/// context.set_value("one".into(), 1.into()).unwrap(); // Do proper error handling here -/// context.set_value("two".into(), 2.into()).unwrap(); // Do proper error handling here -/// context.set_value("three".into(), 3.into()).unwrap(); // Do proper error handling here -/// assert_eq!(eval_with_context_mut("one + two + three", &mut context), Ok(Value::from(6))); +/// let mut context = HashMapContext::::new(); +/// context.set_value("one".into(), Value::from_int(1)).unwrap(); // Do proper error handling here +/// context.set_value("two".into(), Value::from_int(2)).unwrap(); // Do proper error handling here +/// context.set_value("three".into(), Value::from_int(3)).unwrap(); // Do proper error handling here +/// assert_eq!(eval_with_context_mut("one + two + three", &mut context), Ok(Value::from_int(6))); /// ``` /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* pub fn eval_with_context_mut( string: &str, context: &mut C, -) -> EvalexprResult { +) -> EvalexprResultValue { tree::tokens_to_operator_tree(token::tokenize(string)?)?.eval_with_context_mut(context) } @@ -71,19 +80,21 @@ pub fn eval_with_context_mut( /// /// let precomputed = build_operator_tree("one + two + three").unwrap(); // Do proper error handling here /// -/// let mut context = HashMapContext::new(); -/// context.set_value("one".into(), 1.into()).unwrap(); // Do proper error handling here -/// context.set_value("two".into(), 2.into()).unwrap(); // Do proper error handling here -/// context.set_value("three".into(), 3.into()).unwrap(); // Do proper error handling here +/// let mut context = HashMapContext::::new(); +/// context.set_value("one".into(), Value::from_int(1)).unwrap(); // Do proper error handling here +/// context.set_value("two".into(), Value::from_int(2)).unwrap(); // Do proper error handling here +/// context.set_value("three".into(), Value::from_int(3)).unwrap(); // Do proper error handling here /// -/// assert_eq!(precomputed.eval_with_context(&context), Ok(Value::from(6))); +/// assert_eq!(precomputed.eval_with_context(&context), Ok(Value::from_int(6))); /// -/// context.set_value("three".into(), 5.into()).unwrap(); // Do proper error handling here -/// assert_eq!(precomputed.eval_with_context(&context), Ok(Value::from(8))); +/// context.set_value("three".into(), Value::from_int(5)).unwrap(); // Do proper error handling here +/// assert_eq!(precomputed.eval_with_context(&context), Ok(Value::from_int(8))); /// ``` /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn build_operator_tree(string: &str) -> EvalexprResult { +pub fn build_operator_tree( + string: &str, +) -> EvalexprResult, NumericTypes> { tree::tokens_to_operator_tree(token::tokenize(string)?) } @@ -91,56 +102,65 @@ pub fn build_operator_tree(string: &str) -> EvalexprResult { /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* pub fn eval_string(string: &str) -> EvalexprResult { - eval_string_with_context_mut(string, &mut HashMapContext::new()) + eval_string_with_context_mut(string, &mut HashMapContext::::new()) } /// Evaluate the given expression string into an integer. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_int(string: &str) -> EvalexprResult { - eval_int_with_context_mut(string, &mut HashMapContext::new()) +pub fn eval_int( + string: &str, +) -> EvalexprResult<::Int> { + eval_int_with_context_mut(string, &mut HashMapContext::::new()) } /// Evaluate the given expression string into a float. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_float(string: &str) -> EvalexprResult { - eval_float_with_context_mut(string, &mut HashMapContext::new()) +pub fn eval_float( + string: &str, +) -> EvalexprResult<::Float> { + eval_float_with_context_mut(string, &mut HashMapContext::::new()) } /// Evaluate the given expression string into a float. /// If the result of the expression is an integer, it is silently converted into a float. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_number(string: &str) -> EvalexprResult { - eval_number_with_context_mut(string, &mut HashMapContext::new()) +pub fn eval_number( + string: &str, +) -> EvalexprResult<::Float> { + eval_number_with_context_mut(string, &mut HashMapContext::::new()) } /// Evaluate the given expression string into a boolean. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* pub fn eval_boolean(string: &str) -> EvalexprResult { - eval_boolean_with_context_mut(string, &mut HashMapContext::new()) + eval_boolean_with_context_mut(string, &mut HashMapContext::::new()) } /// Evaluate the given expression string into a tuple. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* pub fn eval_tuple(string: &str) -> EvalexprResult { - eval_tuple_with_context_mut(string, &mut HashMapContext::new()) + eval_tuple_with_context_mut(string, &mut HashMapContext::::new()) } /// Evaluate the given expression string into an empty value. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* pub fn eval_empty(string: &str) -> EvalexprResult { - eval_empty_with_context_mut(string, &mut HashMapContext::new()) + eval_empty_with_context_mut(string, &mut HashMapContext::::new()) } /// Evaluate the given expression string into a string with the given context. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_string_with_context(string: &str, context: &C) -> EvalexprResult { +pub fn eval_string_with_context( + string: &str, + context: &C, +) -> EvalexprResult { match eval_with_context(string, context) { Ok(Value::String(string)) => Ok(string), Ok(value) => Err(EvalexprError::expected_string(value)), @@ -151,7 +171,10 @@ pub fn eval_string_with_context(string: &str, context: &C) -> Evalex /// Evaluate the given expression string into an integer with the given context. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_int_with_context(string: &str, context: &C) -> EvalexprResult { +pub fn eval_int_with_context( + string: &str, + context: &C, +) -> EvalexprResult<::Int, C::NumericTypes> { match eval_with_context(string, context) { Ok(Value::Int(int)) => Ok(int), Ok(value) => Err(EvalexprError::expected_int(value)), @@ -162,7 +185,10 @@ pub fn eval_int_with_context(string: &str, context: &C) -> EvalexprR /// Evaluate the given expression string into a float with the given context. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_float_with_context(string: &str, context: &C) -> EvalexprResult { +pub fn eval_float_with_context( + string: &str, + context: &C, +) -> EvalexprResult<::Float, C::NumericTypes> { match eval_with_context(string, context) { Ok(Value::Float(float)) => Ok(float), Ok(value) => Err(EvalexprError::expected_float(value)), @@ -177,10 +203,12 @@ pub fn eval_float_with_context(string: &str, context: &C) -> Evalexp pub fn eval_number_with_context( string: &str, context: &C, -) -> EvalexprResult { +) -> EvalexprResult<::Float, C::NumericTypes> { match eval_with_context(string, context) { Ok(Value::Float(float)) => Ok(float), - Ok(Value::Int(int)) => Ok(int as FloatType), + Ok(Value::Int(int)) => Ok(::int_as_float( + &int, + )), Ok(value) => Err(EvalexprError::expected_number(value)), Err(error) => Err(error), } @@ -189,7 +217,10 @@ pub fn eval_number_with_context( /// Evaluate the given expression string into a boolean with the given context. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_boolean_with_context(string: &str, context: &C) -> EvalexprResult { +pub fn eval_boolean_with_context( + string: &str, + context: &C, +) -> EvalexprResult { match eval_with_context(string, context) { Ok(Value::Boolean(boolean)) => Ok(boolean), Ok(value) => Err(EvalexprError::expected_boolean(value)), @@ -200,7 +231,10 @@ pub fn eval_boolean_with_context(string: &str, context: &C) -> Evale /// Evaluate the given expression string into a tuple with the given context. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_tuple_with_context(string: &str, context: &C) -> EvalexprResult { +pub fn eval_tuple_with_context( + string: &str, + context: &C, +) -> EvalexprResult, C::NumericTypes> { match eval_with_context(string, context) { Ok(Value::Tuple(tuple)) => Ok(tuple), Ok(value) => Err(EvalexprError::expected_tuple(value)), @@ -211,7 +245,10 @@ pub fn eval_tuple_with_context(string: &str, context: &C) -> Evalexp /// Evaluate the given expression string into an empty value with the given context. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* -pub fn eval_empty_with_context(string: &str, context: &C) -> EvalexprResult { +pub fn eval_empty_with_context( + string: &str, + context: &C, +) -> EvalexprResult { match eval_with_context(string, context) { Ok(Value::Empty) => Ok(EMPTY_VALUE), Ok(value) => Err(EvalexprError::expected_empty(value)), @@ -225,7 +262,7 @@ pub fn eval_empty_with_context(string: &str, context: &C) -> Evalexp pub fn eval_string_with_context_mut( string: &str, context: &mut C, -) -> EvalexprResult { +) -> EvalexprResult { match eval_with_context_mut(string, context) { Ok(Value::String(string)) => Ok(string), Ok(value) => Err(EvalexprError::expected_string(value)), @@ -239,7 +276,7 @@ pub fn eval_string_with_context_mut( pub fn eval_int_with_context_mut( string: &str, context: &mut C, -) -> EvalexprResult { +) -> EvalexprResult<::Int, C::NumericTypes> { match eval_with_context_mut(string, context) { Ok(Value::Int(int)) => Ok(int), Ok(value) => Err(EvalexprError::expected_int(value)), @@ -253,7 +290,7 @@ pub fn eval_int_with_context_mut( pub fn eval_float_with_context_mut( string: &str, context: &mut C, -) -> EvalexprResult { +) -> EvalexprResult<::Float, C::NumericTypes> { match eval_with_context_mut(string, context) { Ok(Value::Float(float)) => Ok(float), Ok(value) => Err(EvalexprError::expected_float(value)), @@ -268,10 +305,12 @@ pub fn eval_float_with_context_mut( pub fn eval_number_with_context_mut( string: &str, context: &mut C, -) -> EvalexprResult { +) -> EvalexprResult<::Float, C::NumericTypes> { match eval_with_context_mut(string, context) { Ok(Value::Float(float)) => Ok(float), - Ok(Value::Int(int)) => Ok(int as FloatType), + Ok(Value::Int(int)) => Ok(::int_as_float( + &int, + )), Ok(value) => Err(EvalexprError::expected_number(value)), Err(error) => Err(error), } @@ -283,7 +322,7 @@ pub fn eval_number_with_context_mut( pub fn eval_boolean_with_context_mut( string: &str, context: &mut C, -) -> EvalexprResult { +) -> EvalexprResult { match eval_with_context_mut(string, context) { Ok(Value::Boolean(boolean)) => Ok(boolean), Ok(value) => Err(EvalexprError::expected_boolean(value)), @@ -297,7 +336,7 @@ pub fn eval_boolean_with_context_mut( pub fn eval_tuple_with_context_mut( string: &str, context: &mut C, -) -> EvalexprResult { +) -> EvalexprResult, C::NumericTypes> { match eval_with_context_mut(string, context) { Ok(Value::Tuple(tuple)) => Ok(tuple), Ok(value) => Err(EvalexprError::expected_tuple(value)), @@ -311,7 +350,7 @@ pub fn eval_tuple_with_context_mut( pub fn eval_empty_with_context_mut( string: &str, context: &mut C, -) -> EvalexprResult { +) -> EvalexprResult { match eval_with_context_mut(string, context) { Ok(Value::Empty) => Ok(EMPTY_VALUE), Ok(value) => Err(EvalexprError::expected_empty(value)), diff --git a/src/lib.rs b/src/lib.rs index 763e94b9..5a090deb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,13 +13,13 @@ //! ```rust //! use evalexpr::*; //! -//! assert_eq!(eval("1 + 2 + 3"), Ok(Value::from(6))); +//! assert_eq!(eval("1 + 2 + 3"), Ok(Value::from_int(6))); //! // `eval` returns a variant of the `Value` enum, //! // while `eval_[type]` returns the respective type directly. //! // Both can be used interchangeably. //! assert_eq!(eval_int("1 + 2 + 3"), Ok(6)); -//! assert_eq!(eval("1 /* inline comments are supported */ - 2 * 3 // as are end-of-line comments"), Ok(Value::from(-5))); -//! assert_eq!(eval("1.0 + 2 * 3"), Ok(Value::from(7.0))); +//! assert_eq!(eval("1 /* inline comments are supported */ - 2 * 3 // as are end-of-line comments"), Ok(Value::from_int(-5))); +//! assert_eq!(eval("1.0 + 2 * 3"), Ok(Value::from_float(7.0))); //! assert_eq!(eval("true && 4 > 2"), Ok(Value::from(true))); //! ``` //! @@ -28,14 +28,14 @@ //! ```rust //! use evalexpr::*; //! -//! let mut context = HashMapContext::new(); +//! let mut context = HashMapContext::::new(); //! // Assign 5 to a like this //! assert_eq!(eval_empty_with_context_mut("a = 5", &mut context), Ok(EMPTY_VALUE)); //! // The HashMapContext is type safe, so this will fail now //! assert_eq!(eval_empty_with_context_mut("a = 5.0", &mut context), -//! Err(EvalexprError::expected_int(Value::from(5.0)))); +//! Err(EvalexprError::expected_int(Value::from_float(5.0)))); //! // We can check which value the context stores for a like this -//! assert_eq!(context.get_value("a"), Some(&Value::from(5))); +//! assert_eq!(context.get_value("a"), Some(&Value::from_int(5))); //! // And use the value in another expression like this //! assert_eq!(eval_int_with_context_mut("a = a + 2; a", &mut context), Ok(7)); //! // It is also possible to save a bit of typing by using an operator-assignment operator @@ -47,9 +47,9 @@ //! ```rust //! use evalexpr::*; //! -//! let context = context_map! { -//! "five" => 5, -//! "twelve" => 12, +//! let context: HashMapContext = context_map! { +//! "five" => int 5, +//! "twelve" => int 12, //! "f" => Function::new(|argument| { //! if let Ok(int) = argument.as_int() { //! Ok(Value::Int(int / 2)) @@ -83,16 +83,16 @@ //! ```rust //! use evalexpr::*; //! -//! let precompiled = build_operator_tree("a * b - c > 5").unwrap(); // Do proper error handling here +//! let precompiled = build_operator_tree::("a * b - c > 5").unwrap(); // Do proper error handling here //! //! let mut context = context_map! { -//! "a" => 6, -//! "b" => 2, -//! "c" => 3 +//! "a" => int 6, +//! "b" => int 2, +//! "c" => int 3, //! }.unwrap(); // Do proper error handling here //! assert_eq!(precompiled.eval_with_context(&context), Ok(Value::from(true))); //! -//! context.set_value("c".into(), 8.into()).unwrap(); // Do proper error handling here +//! context.set_value("c".into(), Value::from_int(8)).unwrap(); // Do proper error handling here //! assert_eq!(precompiled.eval_with_context(&context), Ok(Value::from(false))); //! // `Node::eval_with_context` returns a variant of the `Value` enum, //! // while `Node::eval_[type]_with_context` returns the respective type directly. @@ -165,9 +165,9 @@ //! ```rust //! use evalexpr::*; //! -//! assert_eq!(eval("1 / 2"), Ok(Value::from(0))); -//! assert_eq!(eval("1.0 / 2"), Ok(Value::from(0.5))); -//! assert_eq!(eval("2^2"), Ok(Value::from(4.0))); +//! assert_eq!(eval("1 / 2"), Ok(Value::from_int(0))); +//! assert_eq!(eval("1.0 / 2"), Ok(Value::from_float(0.5))); +//! assert_eq!(eval("2^2"), Ok(Value::from_float(4.0))); //! ``` //! //! #### The Aggregation Operator @@ -181,7 +181,7 @@ //! use evalexpr::*; //! //! assert_eq!(eval("1, \"b\", 3"), -//! Ok(Value::from(vec![Value::from(1), Value::from("b"), Value::from(3)]))); +//! Ok(Value::from(vec![Value::from_int(1), Value::from("b"), Value::from_int(3)]))); //! ``` //! //! To create nested tuples, use parentheses: @@ -190,8 +190,8 @@ //! use evalexpr::*; //! //! assert_eq!(eval("1, 2, (true, \"b\")"), Ok(Value::from(vec![ -//! Value::from(1), -//! Value::from(2), +//! Value::from_int(1), +//! Value::from_int(2), //! Value::from(vec![ //! Value::from(true), //! Value::from("b") @@ -210,13 +210,13 @@ //! ```rust //! use evalexpr::*; //! -//! let mut context = HashMapContext::new(); +//! let mut context = HashMapContext::::new(); //! assert_eq!(eval_with_context("a = 5", &context), Err(EvalexprError::ContextNotMutable)); //! assert_eq!(eval_empty_with_context_mut("a = 5", &mut context), Ok(EMPTY_VALUE)); //! assert_eq!(eval_empty_with_context_mut("a = 5.0", &mut context), -//! Err(EvalexprError::expected_int(5.0.into()))); +//! Err(EvalexprError::expected_int(Value::from_float(5.0)))); //! assert_eq!(eval_int_with_context("a", &context), Ok(5)); -//! assert_eq!(context.get_value("a"), Some(5.into()).as_ref()); +//! assert_eq!(context.get_value("a"), Some(Value::from_int(5)).as_ref()); //! ``` //! //! For each binary operator, there exists an equivalent operator-assignment operator. @@ -241,9 +241,9 @@ //! ```rust //! use evalexpr::*; //! -//! let mut context = HashMapContext::new(); +//! let mut context = HashMapContext::::new(); //! assert_eq!(eval("1;2;3;4;"), Ok(Value::Empty)); -//! assert_eq!(eval("1;2;3;4"), Ok(4.into())); +//! assert_eq!(eval("1;2;3;4"), Ok(Value::from_int(4))); //! //! // Initialization of variables via script //! assert_eq!(eval_empty_with_context_mut("hp = 1; max_hp = 5; heal_amount = 3;", &mut context), @@ -271,15 +271,15 @@ //! // The context is not preserved between eval calls //! assert_eq!(eval("a"), Err(EvalexprError::VariableIdentifierNotFound("a".to_string()))); //! -//! let mut context = HashMapContext::new(); +//! let mut context = HashMapContext::::new(); //! assert_eq!(eval_with_context_mut("a = 5;", &mut context), Ok(Value::from(()))); //! // Assignments require mutable contexts //! assert_eq!(eval_with_context("a = 6", &context), Err(EvalexprError::ContextNotMutable)); //! // The HashMapContext is type safe //! assert_eq!(eval_with_context_mut("a = 5.5", &mut context), -//! Err(EvalexprError::ExpectedInt { actual: Value::from(5.5) })); +//! Err(EvalexprError::ExpectedInt { actual: Value::from_float(5.5) })); //! // Reading a variable does not require a mutable context -//! assert_eq!(eval_with_context("a", &context), Ok(Value::from(5))); +//! assert_eq!(eval_with_context("a", &context), Ok(Value::from_int(5))); //! //! ``` //! @@ -299,16 +299,16 @@ //! ```rust //! use evalexpr::*; //! -//! let mut context = HashMapContext::new(); +//! let mut context = HashMapContext::::new(); //! // We can set variables in code like this... -//! context.set_value("a".into(), 5.into()); +//! context.set_value("a".into(), Value::from_int(5)); //! // ...and read from them in expressions //! assert_eq!(eval_int_with_context("a", &context), Ok(5)); //! // We can write or overwrite variables in expressions... //! assert_eq!(eval_with_context_mut("a = 10; b = 1.0;", &mut context), Ok(().into())); //! // ...and read the value in code like this -//! assert_eq!(context.get_value("a"), Some(&Value::from(10))); -//! assert_eq!(context.get_value("b"), Some(&Value::from(1.0))); +//! assert_eq!(context.get_value("a"), Some(&Value::from_int(10))); +//! assert_eq!(context.get_value("b"), Some(&Value::from_float(1.0))); //! ``` //! //! Contexts are also required for user-defined functions. @@ -317,8 +317,8 @@ //! ```rust //! use evalexpr::*; //! -//! let context = context_map!{ -//! "f" => Function::new(|args| Ok(Value::from(args.as_int()? + 5))), +//! let context: HashMapContext = context_map!{ +//! "f" => Function::new(|args| Ok(Value::from_int(args.as_int()? + 5))), //! }.unwrap_or_else(|error| panic!("Error creating context: {}", error)); //! assert_eq!(eval_int_with_context("f 5", &context), Ok(10)); //! ``` @@ -332,8 +332,8 @@ //! //! ```rust //! use evalexpr::*; -//! let mut context = HashMapContext::new(); -//! assert_eq!(eval_with_context("max(1,3)",&context),Ok(Value::from(3))); +//! let mut context = HashMapContext::::new(); +//! assert_eq!(eval_with_context("max(1,3)",&context),Ok(Value::from_int(3))); //! context.set_builtin_functions_disabled(true).unwrap(); // Do proper error handling here //! assert_eq!(eval_with_context("max(1,3)",&context),Err(EvalexprError::FunctionIdentifierNotFound(String::from("max")))); //! ``` @@ -550,7 +550,7 @@ //! // In ron format, strings are surrounded by " //! let serialized_free = "\"five * five\""; //! match ron::de::from_str::(serialized_free) { -//! Ok(free) => assert_eq!(free.eval_with_context(&context), Ok(Value::from(25))), +//! Ok(free) => assert_eq!(free.eval_with_context(&context), Ok(Value::from_int(25))), //! Err(error) => { //! () // Handle error //! } @@ -563,26 +563,19 @@ //! The crate also implements `Serialize` and `Deserialize` for the `HashMapContext`, //! but note that only the variables get (de)serialized, not the functions. //! -//! ## License +//! ## Licensing //! -//! This crate is primarily distributed under the terms of the MIT license. -//! See [LICENSE](LICENSE) for details. +//! This crate is primarily distributed under the terms of the AGPL3 license. +//! See [LICENSE](/LICENSE) for details. +//! If you require a different licensing option for your project, contact me at `isibboi at gmail.com`. +//! +//! Contributions to this crate are assumed to be licensed under the [MIT License](https://opensource.org/license/mit). //! #![deny(missing_docs)] #![forbid(unsafe_code)] #![allow(clippy::get_first)] -#[cfg(feature = "regex_support")] -extern crate regex; -#[cfg(test)] -extern crate ron; -#[cfg(feature = "serde_support")] -extern crate serde; -#[cfg(feature = "serde_support")] -#[macro_use] -extern crate serde_derive; - pub use crate::{ context::{ Context, ContextWithMutableFunctions, ContextWithMutableVariables, EmptyContext, @@ -594,12 +587,16 @@ pub use crate::{ operator::Operator, token::PartialToken, tree::Node, - value::{value_type::ValueType, EmptyType, FloatType, IntType, TupleType, Value, EMPTY_VALUE}, + value::{ + numeric_types::{DefaultNumericTypes, EvalexprFloat, EvalexprInt, EvalexprNumericTypes}, + value_type::ValueType, + EmptyType, TupleType, Value, EMPTY_VALUE, + }, }; mod context; pub mod error; -#[cfg(feature = "serde_support")] +#[cfg(feature = "serde")] mod feature_serde; mod function; mod interface; diff --git a/src/operator/display.rs b/src/operator/display.rs index 12351dd4..ec490787 100644 --- a/src/operator/display.rs +++ b/src/operator/display.rs @@ -4,7 +4,7 @@ use std::fmt::{Display, Error, Formatter}; use crate::operator::*; -impl Display for Operator { +impl Display for Operator { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { use crate::operator::Operator::*; match self { diff --git a/src/operator/mod.rs b/src/operator/mod.rs index 386357ae..65e6f9ef 100644 --- a/src/operator/mod.rs +++ b/src/operator/mod.rs @@ -1,12 +1,15 @@ use crate::function::builtin::builtin_function; +use crate::value::numeric_types::{ + DefaultNumericTypes, EvalexprFloat, EvalexprInt, EvalexprNumericTypes, +}; use crate::{context::Context, error::*, value::Value, ContextWithMutableVariables}; mod display; /// An enum that represents operators in the operator tree. #[derive(Debug, PartialEq, Clone)] -pub enum Operator { +pub enum Operator { /// A root node in the operator tree. /// The whole expression is stored under a root node, as well as each subexpression surrounded by parentheses. RootNode, @@ -72,7 +75,7 @@ pub enum Operator { /// A constant value. Const { /** The value of the constant. */ - value: Value, + value: Value, }, /// A write to a variable identifier. VariableIdentifierWrite { @@ -91,8 +94,8 @@ pub enum Operator { }, } -impl Operator { - pub(crate) fn value(value: Value) -> Self { +impl Operator { + pub(crate) fn value(value: Value) -> Self { Operator::Const { value } } @@ -178,11 +181,11 @@ impl Operator { } /// Evaluates the operator with the given arguments and context. - pub(crate) fn eval( + pub(crate) fn eval>( &self, - arguments: &[Value], + arguments: &[Value], context: &C, - ) -> EvalexprResult { + ) -> EvalexprResultValue { use crate::operator::Operator::*; match self { RootNode => { @@ -203,15 +206,7 @@ impl Operator { result.push_str(&b); Ok(Value::String(result)) } else if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { - let result = a.checked_add(b); - if let Some(result) = result { - Ok(Value::Int(result)) - } else { - Err(EvalexprError::addition_error( - arguments[0].clone(), - arguments[1].clone(), - )) - } + a.checked_add(&b).map(Value::Int) } else if let (Ok(a), Ok(b)) = (arguments[0].as_number(), arguments[1].as_number()) { Ok(Value::Float(a + b)) @@ -231,15 +226,7 @@ impl Operator { arguments[1].as_number()?; if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { - let result = a.checked_sub(b); - if let Some(result) = result { - Ok(Value::Int(result)) - } else { - Err(EvalexprError::subtraction_error( - arguments[0].clone(), - arguments[1].clone(), - )) - } + a.checked_sub(&b).map(Value::Int) } else { Ok(Value::Float( arguments[0].as_number()? - arguments[1].as_number()?, @@ -251,12 +238,7 @@ impl Operator { arguments[0].as_number()?; if let Ok(a) = arguments[0].as_int() { - let result = a.checked_neg(); - if let Some(result) = result { - Ok(Value::Int(result)) - } else { - Err(EvalexprError::negation_error(arguments[0].clone())) - } + a.checked_neg().map(Value::Int) } else { Ok(Value::Float(-arguments[0].as_number()?)) } @@ -267,15 +249,7 @@ impl Operator { arguments[1].as_number()?; if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { - let result = a.checked_mul(b); - if let Some(result) = result { - Ok(Value::Int(result)) - } else { - Err(EvalexprError::multiplication_error( - arguments[0].clone(), - arguments[1].clone(), - )) - } + a.checked_mul(&b).map(Value::Int) } else { Ok(Value::Float( arguments[0].as_number()? * arguments[1].as_number()?, @@ -288,15 +262,7 @@ impl Operator { arguments[1].as_number()?; if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { - let result = a.checked_div(b); - if let Some(result) = result { - Ok(Value::Int(result)) - } else { - Err(EvalexprError::division_error( - arguments[0].clone(), - arguments[1].clone(), - )) - } + a.checked_div(&b).map(Value::Int) } else { Ok(Value::Float( arguments[0].as_number()? / arguments[1].as_number()?, @@ -309,15 +275,7 @@ impl Operator { arguments[1].as_number()?; if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { - let result = a.checked_rem(b); - if let Some(result) = result { - Ok(Value::Int(result)) - } else { - Err(EvalexprError::modulation_error( - arguments[0].clone(), - arguments[1].clone(), - )) - } + a.checked_rem(&b).map(Value::Int) } else { Ok(Value::Float( arguments[0].as_number()? % arguments[1].as_number()?, @@ -330,7 +288,7 @@ impl Operator { arguments[1].as_number()?; Ok(Value::Float( - arguments[0].as_number()?.powf(arguments[1].as_number()?), + arguments[0].as_number()?.pow(&arguments[1].as_number()?), )) }, Eq => { @@ -477,11 +435,13 @@ impl Operator { } /// Evaluates the operator with the given arguments and mutable context. - pub(crate) fn eval_mut( + pub(crate) fn eval_mut< + C: ContextWithMutableVariables + Context, + >( &self, - arguments: &[Value], + arguments: &[Value], context: &mut C, - ) -> EvalexprResult { + ) -> EvalexprResultValue { use crate::operator::Operator::*; match self { Assign => { diff --git a/src/token/display.rs b/src/token/display.rs index 35f20876..8b8b65fd 100644 --- a/src/token/display.rs +++ b/src/token/display.rs @@ -1,8 +1,11 @@ use std::fmt; -use crate::token::{PartialToken, Token}; +use crate::{ + token::{PartialToken, Token}, + value::numeric_types::EvalexprNumericTypes, +}; -impl fmt::Display for Token { +impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { use self::Token::*; match self { @@ -53,7 +56,7 @@ impl fmt::Display for Token { } } -impl fmt::Display for PartialToken { +impl fmt::Display for PartialToken { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { use self::PartialToken::*; match self { diff --git a/src/token/mod.rs b/src/token/mod.rs index ea228902..f4183d09 100644 --- a/src/token/mod.rs +++ b/src/token/mod.rs @@ -1,12 +1,14 @@ +use std::str::FromStr; + use crate::{ error::{EvalexprError, EvalexprResult}, - value::{FloatType, IntType}, + value::numeric_types::{DefaultNumericTypes, EvalexprInt, EvalexprNumericTypes}, }; mod display; #[derive(Clone, PartialEq, Debug)] -pub enum Token { +pub enum Token { // Arithmetic Plus, Minus, @@ -47,17 +49,17 @@ pub enum Token { // Values, Variables and Functions Identifier(String), - Float(FloatType), - Int(IntType), + Float(NumericTypes::Float), + Int(NumericTypes::Int), Boolean(bool), String(String), } /// A partial token is an input character whose meaning depends on the characters around it. #[derive(Clone, Debug, PartialEq)] -pub enum PartialToken { +pub enum PartialToken { /// A partial token that unambiguously maps to a single token. - Token(Token), + Token(Token), /// A partial token that is a literal. Literal(String), /// A plus character '+'. @@ -89,7 +91,9 @@ pub enum PartialToken { } // Make this a const fn as soon as is_whitespace and to_string get stable (issue #57563) -fn char_to_partial_token(c: char) -> PartialToken { +fn char_to_partial_token( + c: char, +) -> PartialToken { match c { '+' => PartialToken::Plus, '-' => PartialToken::Minus, @@ -121,7 +125,7 @@ fn char_to_partial_token(c: char) -> PartialToken { } } -impl Token { +impl Token { #[cfg(not(tarpaulin_include))] pub(crate) const fn is_leftsided_value(&self) -> bool { match self { @@ -229,7 +233,9 @@ impl Token { } /// Parses an escape sequence within a string literal. -fn parse_escape_sequence>(iter: &mut Iter) -> EvalexprResult { +fn parse_escape_sequence, NumericTypes: EvalexprNumericTypes>( + iter: &mut Iter, +) -> EvalexprResult { match iter.next() { Some('"') => Ok('"'), Some('\\') => Ok('\\'), @@ -244,9 +250,9 @@ fn parse_escape_sequence>(iter: &mut Iter) -> Evalex /// The string is terminated by a double quote `"`. /// Occurrences of `"` within the string can be escaped with `\`. /// The backslash needs to be escaped with another backslash `\`. -fn parse_string_literal>( +fn parse_string_literal, NumericTypes: EvalexprNumericTypes>( mut iter: &mut Iter, -) -> EvalexprResult { +) -> EvalexprResult, NumericTypes> { let mut result = String::new(); while let Some(c) = iter.next() { @@ -260,7 +266,9 @@ fn parse_string_literal>( Err(EvalexprError::UnmatchedDoubleQuote) } -fn try_skip_comment(iter: &mut std::iter::Peekable>) -> EvalexprResult { +fn try_skip_comment( + iter: &mut std::iter::Peekable>, +) -> EvalexprResult { let mut matched = false; if let Some(lookahead) = iter.peek() { if *lookahead == '/' { @@ -296,7 +304,9 @@ fn try_skip_comment(iter: &mut std::iter::Peekable>) -> Eval } /// Converts a string to a vector of partial tokens. -fn str_to_partial_tokens(string: &str) -> EvalexprResult> { +fn str_to_partial_tokens( + string: &str, +) -> EvalexprResult>, NumericTypes> { let mut result = Vec::new(); let mut iter = string.chars().peekable(); @@ -331,7 +341,9 @@ fn str_to_partial_tokens(string: &str) -> EvalexprResult> { } /// Resolves all partial tokens by converting them to complex tokens. -fn partial_tokens_to_tokens(mut tokens: &[PartialToken]) -> EvalexprResult> { +fn partial_tokens_to_tokens( + mut tokens: &[PartialToken], +) -> EvalexprResult>, NumericTypes> { let mut result = Vec::new(); while !tokens.is_empty() { let first = tokens[0].clone(); @@ -388,9 +400,9 @@ fn partial_tokens_to_tokens(mut tokens: &[PartialToken]) -> EvalexprResult { cutoff = 1; - if let Ok(number) = parse_dec_or_hex(&literal) { + if let Ok(number) = parse_dec_or_hex::(&literal) { Some(Token::Int(number)) - } else if let Ok(number) = literal.parse::() { + } else if let Ok(number) = literal.parse::() { Some(Token::Float(number)) } else if let Ok(boolean) = literal.parse::() { Some(Token::Boolean(boolean)) @@ -403,8 +415,8 @@ fn partial_tokens_to_tokens(mut tokens: &[PartialToken]) -> EvalexprResult { - if let Ok(number) = - format!("{}{}{}", literal, second, third).parse::() + if let Ok(number) = format!("{}{}{}", literal, second, third) + .parse::() { cutoff = 3; Some(Token::Float(number)) @@ -475,21 +487,28 @@ fn partial_tokens_to_tokens(mut tokens: &[PartialToken]) -> EvalexprResult EvalexprResult> { +pub(crate) fn tokenize( + string: &str, +) -> EvalexprResult>, NumericTypes> { partial_tokens_to_tokens(&str_to_partial_tokens(string)?) } -fn parse_dec_or_hex(literal: &str) -> Result { +fn parse_dec_or_hex( + literal: &str, +) -> Result { if let Some(literal) = literal.strip_prefix("0x") { - IntType::from_str_radix(literal, 16) + NumericTypes::Int::from_hex_str(literal) } else { - IntType::from_str_radix(literal, 10) + NumericTypes::Int::from_str(literal).map_err(|_| ()) } } #[cfg(test)] mod tests { - use crate::token::{char_to_partial_token, tokenize, Token}; + use crate::{ + token::{char_to_partial_token, tokenize, Token}, + value::numeric_types::DefaultNumericTypes, + }; use std::fmt::Write; #[test] @@ -501,7 +520,7 @@ mod tests { for char in chars { assert_eq!( format!("{}", char), - format!("{}", char_to_partial_token(char)) + format!("{}", char_to_partial_token::(char)) ); } } @@ -510,7 +529,7 @@ mod tests { fn test_token_display() { let token_string = "+ - * / % ^ == != > < >= <= && || ! ( ) = += -= *= /= %= ^= &&= ||= , ; "; - let tokens = tokenize(token_string).unwrap(); + let tokens = tokenize::(token_string).unwrap(); let mut result_string = String::new(); for token in tokens { @@ -532,7 +551,7 @@ mod tests { &&= ||= , ; "; - let tokens = tokenize(token_string_with_comments).unwrap(); + let tokens = tokenize::(token_string_with_comments).unwrap(); let mut result_string = String::new(); for token in tokens { @@ -544,7 +563,7 @@ mod tests { #[test] fn assignment_lhs_is_identifier() { - let tokens = tokenize("a = 1").unwrap(); + let tokens = tokenize::("a = 1").unwrap(); assert_eq!( tokens.as_slice(), [ diff --git a/src/tree/iter.rs b/src/tree/iter.rs index 05243616..728895bb 100644 --- a/src/tree/iter.rs +++ b/src/tree/iter.rs @@ -1,21 +1,21 @@ -use crate::{operator::Operator, Node}; +use crate::{operator::Operator, value::numeric_types::EvalexprNumericTypes, Node}; use std::slice::{Iter, IterMut}; /// An iterator that traverses an operator tree in pre-order. -pub struct NodeIter<'a> { - stack: Vec>, +pub struct NodeIter<'a, NumericTypes: EvalexprNumericTypes> { + stack: Vec>>, } -impl<'a> NodeIter<'a> { - fn new(node: &'a Node) -> Self { +impl<'a, NumericTypes: EvalexprNumericTypes> NodeIter<'a, NumericTypes> { + fn new(node: &'a Node) -> Self { NodeIter { stack: vec![node.children.iter()], } } } -impl<'a> Iterator for NodeIter<'a> { - type Item = &'a Node; +impl<'a, NumericTypes: EvalexprNumericTypes> Iterator for NodeIter<'a, NumericTypes> { + type Item = &'a Node; fn next(&mut self) -> Option { loop { @@ -42,20 +42,20 @@ impl<'a> Iterator for NodeIter<'a> { } /// An iterator that mutably traverses an operator tree in pre-order. -pub struct OperatorIterMut<'a> { - stack: Vec>, +pub struct OperatorIterMut<'a, NumericTypes: EvalexprNumericTypes> { + stack: Vec>>, } -impl<'a> OperatorIterMut<'a> { - fn new(node: &'a mut Node) -> Self { +impl<'a, NumericTypes: EvalexprNumericTypes> OperatorIterMut<'a, NumericTypes> { + fn new(node: &'a mut Node) -> Self { OperatorIterMut { stack: vec![node.children.iter_mut()], } } } -impl<'a> Iterator for OperatorIterMut<'a> { - type Item = &'a mut Operator; +impl<'a, NumericTypes: EvalexprNumericTypes> Iterator for OperatorIterMut<'a, NumericTypes> { + type Item = &'a mut Operator; fn next(&mut self) -> Option { loop { @@ -81,14 +81,14 @@ impl<'a> Iterator for OperatorIterMut<'a> { } } -impl Node { +impl Node { /// Returns an iterator over all nodes in this tree. - pub fn iter(&self) -> impl Iterator { + pub fn iter(&self) -> impl Iterator> { NodeIter::new(self) } /// Returns a mutable iterator over all operators in this tree. - pub fn iter_operators_mut(&mut self) -> impl Iterator { + pub fn iter_operators_mut(&mut self) -> impl Iterator> { OperatorIterMut::new(self) } } diff --git a/src/tree/mod.rs b/src/tree/mod.rs index e835fd30..d5f61667 100644 --- a/src/tree/mod.rs +++ b/src/tree/mod.rs @@ -1,7 +1,11 @@ use crate::{ + error::EvalexprResultValue, token::Token, - value::{TupleType, EMPTY_VALUE}, - Context, ContextWithMutableVariables, EmptyType, FloatType, HashMapContext, IntType, + value::{ + numeric_types::{DefaultNumericTypes, EvalexprNumericTypes}, + TupleType, EMPTY_VALUE, + }, + Context, ContextWithMutableVariables, EmptyType, HashMapContext, }; use crate::{ @@ -27,20 +31,20 @@ mod iter; /// ```rust /// use evalexpr::*; /// -/// let mut context = HashMapContext::new(); -/// context.set_value("alpha".into(), 2.into()).unwrap(); // Do proper error handling here +/// let mut context = HashMapContext::::new(); +/// context.set_value("alpha".into(), Value::from_int(2)).unwrap(); // Do proper error handling here /// let node = build_operator_tree("1 + alpha").unwrap(); // Do proper error handling here -/// assert_eq!(node.eval_with_context(&context), Ok(Value::from(3))); +/// assert_eq!(node.eval_with_context(&context), Ok(Value::from_int(3))); /// ``` /// #[derive(Debug, PartialEq, Clone)] -pub struct Node { - operator: Operator, - children: Vec, +pub struct Node { + operator: Operator, + children: Vec>, } -impl Node { - fn new(operator: Operator) -> Self { +impl Node { + fn new(operator: Operator) -> Self { Self { children: Vec::new(), operator, @@ -59,7 +63,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let tree = build_operator_tree("a + b + c * f()").unwrap(); // Do proper error handling here + /// let tree = build_operator_tree::("a + b + c * f()").unwrap(); // Do proper error handling here /// let mut iter = tree.iter_identifiers(); /// assert_eq!(iter.next(), Some("a")); /// assert_eq!(iter.next(), Some("b")); @@ -84,7 +88,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let mut tree = build_operator_tree("a + b + c * f()").unwrap(); // Do proper error handling here + /// let mut tree = build_operator_tree::("a + b + c * f()").unwrap(); // Do proper error handling here /// /// for identifier in tree.iter_identifiers_mut() { /// *identifier = String::from("x"); @@ -116,7 +120,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let tree = build_operator_tree("a + f(b + c)").unwrap(); // Do proper error handling here + /// let tree = build_operator_tree::("a + f(b + c)").unwrap(); // Do proper error handling here /// let mut iter = tree.iter_variable_identifiers(); /// assert_eq!(iter.next(), Some("a")); /// assert_eq!(iter.next(), Some("b")); @@ -139,7 +143,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let mut tree = build_operator_tree("a + b + c * f()").unwrap(); // Do proper error handling here + /// let mut tree = build_operator_tree::("a + b + c * f()").unwrap(); // Do proper error handling here /// /// for identifier in tree.iter_variable_identifiers_mut() { /// *identifier = String::from("x"); @@ -170,7 +174,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// let tree = build_operator_tree::("d = a + f(b + c)").unwrap(); // Do proper error handling here /// let mut iter = tree.iter_read_variable_identifiers(); /// assert_eq!(iter.next(), Some("a")); /// assert_eq!(iter.next(), Some("b")); @@ -192,7 +196,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let mut tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// let mut tree = build_operator_tree::("d = a + f(b + c)").unwrap(); // Do proper error handling here /// /// for identifier in tree.iter_read_variable_identifiers_mut() { /// *identifier = String::from("x"); @@ -223,7 +227,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// let tree = build_operator_tree::("d = a + f(b + c)").unwrap(); // Do proper error handling here /// let mut iter = tree.iter_write_variable_identifiers(); /// assert_eq!(iter.next(), Some("d")); /// assert_eq!(iter.next(), None); @@ -243,7 +247,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let mut tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// let mut tree = build_operator_tree::("d = a + f(b + c)").unwrap(); // Do proper error handling here /// /// for identifier in tree.iter_write_variable_identifiers_mut() { /// *identifier = String::from("x"); @@ -274,7 +278,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let tree = build_operator_tree("a + f(b + c)").unwrap(); // Do proper error handling here + /// let tree = build_operator_tree::("a + f(b + c)").unwrap(); // Do proper error handling here /// let mut iter = tree.iter_function_identifiers(); /// assert_eq!(iter.next(), Some("f")); /// assert_eq!(iter.next(), None); @@ -294,7 +298,7 @@ impl Node { /// ```rust /// use evalexpr::*; /// - /// let mut tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// let mut tree = build_operator_tree::("d = a + f(b + c)").unwrap(); // Do proper error handling here /// /// for identifier in tree.iter_function_identifiers_mut() { /// *identifier = String::from("x"); @@ -320,7 +324,10 @@ impl Node { /// Evaluates the operator tree rooted at this node with the given context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_with_context(&self, context: &C) -> EvalexprResult { + pub fn eval_with_context>( + &self, + context: &C, + ) -> EvalexprResultValue { let mut arguments = Vec::new(); for child in self.children() { arguments.push(child.eval_with_context(context)?); @@ -331,10 +338,12 @@ impl Node { /// Evaluates the operator tree rooted at this node with the given mutable context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_with_context_mut( + pub fn eval_with_context_mut< + C: ContextWithMutableVariables + Context, + >( &self, context: &mut C, - ) -> EvalexprResult { + ) -> EvalexprResultValue { let mut arguments = Vec::new(); for child in self.children() { arguments.push(child.eval_with_context_mut(context)?); @@ -345,14 +354,17 @@ impl Node { /// Evaluates the operator tree rooted at this node. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval(&self) -> EvalexprResult { + pub fn eval(&self) -> EvalexprResultValue { self.eval_with_context_mut(&mut HashMapContext::new()) } /// Evaluates the operator tree rooted at this node into a string with an the given context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_string_with_context(&self, context: &C) -> EvalexprResult { + pub fn eval_string_with_context>( + &self, + context: &C, + ) -> EvalexprResult { match self.eval_with_context(context) { Ok(Value::String(string)) => Ok(string), Ok(value) => Err(EvalexprError::expected_string(value)), @@ -363,7 +375,10 @@ impl Node { /// Evaluates the operator tree rooted at this node into a float with an the given context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_float_with_context(&self, context: &C) -> EvalexprResult { + pub fn eval_float_with_context>( + &self, + context: &C, + ) -> EvalexprResult<::Float, NumericTypes> { match self.eval_with_context(context) { Ok(Value::Float(float)) => Ok(float), Ok(value) => Err(EvalexprError::expected_float(value)), @@ -374,7 +389,10 @@ impl Node { /// Evaluates the operator tree rooted at this node into an integer with an the given context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_int_with_context(&self, context: &C) -> EvalexprResult { + pub fn eval_int_with_context>( + &self, + context: &C, + ) -> EvalexprResult<::Int, NumericTypes> { match self.eval_with_context(context) { Ok(Value::Int(int)) => Ok(int), Ok(value) => Err(EvalexprError::expected_int(value)), @@ -386,9 +404,12 @@ impl Node { /// If the result of the expression is an integer, it is silently converted into a float. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_number_with_context(&self, context: &C) -> EvalexprResult { + pub fn eval_number_with_context>( + &self, + context: &C, + ) -> EvalexprResult<::Float, NumericTypes> { match self.eval_with_context(context) { - Ok(Value::Int(int)) => Ok(int as FloatType), + Ok(Value::Int(int)) => Ok(NumericTypes::int_as_float(&int)), Ok(Value::Float(float)) => Ok(float), Ok(value) => Err(EvalexprError::expected_number(value)), Err(error) => Err(error), @@ -398,7 +419,10 @@ impl Node { /// Evaluates the operator tree rooted at this node into a boolean with an the given context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_boolean_with_context(&self, context: &C) -> EvalexprResult { + pub fn eval_boolean_with_context>( + &self, + context: &C, + ) -> EvalexprResult { match self.eval_with_context(context) { Ok(Value::Boolean(boolean)) => Ok(boolean), Ok(value) => Err(EvalexprError::expected_boolean(value)), @@ -409,7 +433,10 @@ impl Node { /// Evaluates the operator tree rooted at this node into a tuple with an the given context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_tuple_with_context(&self, context: &C) -> EvalexprResult { + pub fn eval_tuple_with_context>( + &self, + context: &C, + ) -> EvalexprResult, NumericTypes> { match self.eval_with_context(context) { Ok(Value::Tuple(tuple)) => Ok(tuple), Ok(value) => Err(EvalexprError::expected_tuple(value)), @@ -420,7 +447,10 @@ impl Node { /// Evaluates the operator tree rooted at this node into an empty value with an the given context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_empty_with_context(&self, context: &C) -> EvalexprResult { + pub fn eval_empty_with_context>( + &self, + context: &C, + ) -> EvalexprResult { match self.eval_with_context(context) { Ok(Value::Empty) => Ok(EMPTY_VALUE), Ok(value) => Err(EvalexprError::expected_empty(value)), @@ -431,10 +461,12 @@ impl Node { /// Evaluates the operator tree rooted at this node into a string with an the given mutable context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_string_with_context_mut( + pub fn eval_string_with_context_mut< + C: ContextWithMutableVariables + Context, + >( &self, context: &mut C, - ) -> EvalexprResult { + ) -> EvalexprResult { match self.eval_with_context_mut(context) { Ok(Value::String(string)) => Ok(string), Ok(value) => Err(EvalexprError::expected_string(value)), @@ -445,10 +477,12 @@ impl Node { /// Evaluates the operator tree rooted at this node into a float with an the given mutable context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_float_with_context_mut( + pub fn eval_float_with_context_mut< + C: ContextWithMutableVariables + Context, + >( &self, context: &mut C, - ) -> EvalexprResult { + ) -> EvalexprResult<::Float, NumericTypes> { match self.eval_with_context_mut(context) { Ok(Value::Float(float)) => Ok(float), Ok(value) => Err(EvalexprError::expected_float(value)), @@ -459,10 +493,12 @@ impl Node { /// Evaluates the operator tree rooted at this node into an integer with an the given mutable context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_int_with_context_mut( + pub fn eval_int_with_context_mut< + C: ContextWithMutableVariables + Context, + >( &self, context: &mut C, - ) -> EvalexprResult { + ) -> EvalexprResult<::Int, NumericTypes> { match self.eval_with_context_mut(context) { Ok(Value::Int(int)) => Ok(int), Ok(value) => Err(EvalexprError::expected_int(value)), @@ -474,12 +510,14 @@ impl Node { /// If the result of the expression is an integer, it is silently converted into a float. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_number_with_context_mut( + pub fn eval_number_with_context_mut< + C: ContextWithMutableVariables + Context, + >( &self, context: &mut C, - ) -> EvalexprResult { + ) -> EvalexprResult<::Float, NumericTypes> { match self.eval_with_context_mut(context) { - Ok(Value::Int(int)) => Ok(int as FloatType), + Ok(Value::Int(int)) => Ok(::int_as_float(&int)), Ok(Value::Float(float)) => Ok(float), Ok(value) => Err(EvalexprError::expected_number(value)), Err(error) => Err(error), @@ -489,10 +527,12 @@ impl Node { /// Evaluates the operator tree rooted at this node into a boolean with an the given mutable context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_boolean_with_context_mut( + pub fn eval_boolean_with_context_mut< + C: ContextWithMutableVariables + Context, + >( &self, context: &mut C, - ) -> EvalexprResult { + ) -> EvalexprResult { match self.eval_with_context_mut(context) { Ok(Value::Boolean(boolean)) => Ok(boolean), Ok(value) => Err(EvalexprError::expected_boolean(value)), @@ -503,10 +543,12 @@ impl Node { /// Evaluates the operator tree rooted at this node into a tuple with an the given mutable context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_tuple_with_context_mut( + pub fn eval_tuple_with_context_mut< + C: ContextWithMutableVariables + Context, + >( &self, context: &mut C, - ) -> EvalexprResult { + ) -> EvalexprResult, NumericTypes> { match self.eval_with_context_mut(context) { Ok(Value::Tuple(tuple)) => Ok(tuple), Ok(value) => Err(EvalexprError::expected_tuple(value)), @@ -517,10 +559,12 @@ impl Node { /// Evaluates the operator tree rooted at this node into an empty value with an the given mutable context. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_empty_with_context_mut( + pub fn eval_empty_with_context_mut< + C: ContextWithMutableVariables + Context, + >( &self, context: &mut C, - ) -> EvalexprResult { + ) -> EvalexprResult { match self.eval_with_context_mut(context) { Ok(Value::Empty) => Ok(EMPTY_VALUE), Ok(value) => Err(EvalexprError::expected_empty(value)), @@ -531,21 +575,25 @@ impl Node { /// Evaluates the operator tree rooted at this node into a string. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_string(&self) -> EvalexprResult { + pub fn eval_string(&self) -> EvalexprResult { self.eval_string_with_context_mut(&mut HashMapContext::new()) } /// Evaluates the operator tree rooted at this node into a float. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_float(&self) -> EvalexprResult { + pub fn eval_float( + &self, + ) -> EvalexprResult<::Float, NumericTypes> { self.eval_float_with_context_mut(&mut HashMapContext::new()) } /// Evaluates the operator tree rooted at this node into an integer. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_int(&self) -> EvalexprResult { + pub fn eval_int( + &self, + ) -> EvalexprResult<::Int, NumericTypes> { self.eval_int_with_context_mut(&mut HashMapContext::new()) } @@ -553,52 +601,54 @@ impl Node { /// If the result of the expression is an integer, it is silently converted into a float. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_number(&self) -> EvalexprResult { + pub fn eval_number( + &self, + ) -> EvalexprResult<::Float, NumericTypes> { self.eval_number_with_context_mut(&mut HashMapContext::new()) } /// Evaluates the operator tree rooted at this node into a boolean. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_boolean(&self) -> EvalexprResult { + pub fn eval_boolean(&self) -> EvalexprResult { self.eval_boolean_with_context_mut(&mut HashMapContext::new()) } /// Evaluates the operator tree rooted at this node into a tuple. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_tuple(&self) -> EvalexprResult { + pub fn eval_tuple(&self) -> EvalexprResult, NumericTypes> { self.eval_tuple_with_context_mut(&mut HashMapContext::new()) } /// Evaluates the operator tree rooted at this node into an empty value. /// /// Fails, if one of the operators in the expression tree fails. - pub fn eval_empty(&self) -> EvalexprResult { + pub fn eval_empty(&self) -> EvalexprResult { self.eval_empty_with_context_mut(&mut HashMapContext::new()) } /// Returns the children of this node as a slice. - pub fn children(&self) -> &[Node] { + pub fn children(&self) -> &[Node] { &self.children } /// Returns the operator associated with this node. - pub fn operator(&self) -> &Operator { + pub fn operator(&self) -> &Operator { &self.operator } /// Returns a mutable reference to the vector containing the children of this node. /// /// WARNING: Writing to this might have unexpected results, as some operators require certain amounts and types of arguments. - pub fn children_mut(&mut self) -> &mut Vec { + pub fn children_mut(&mut self) -> &mut Vec> { &mut self.children } /// Returns a mutable reference to the operator associated with this node. /// /// WARNING: Writing to this might have unexpected results, as some operators require different amounts and types of arguments. - pub fn operator_mut(&mut self) -> &mut Operator { + pub fn operator_mut(&mut self) -> &mut Operator { &mut self.operator } @@ -614,7 +664,11 @@ impl Node { } } - fn insert_back_prioritized(&mut self, node: Node, is_root_node: bool) -> EvalexprResult<()> { + fn insert_back_prioritized( + &mut self, + node: Node, + is_root_node: bool, + ) -> EvalexprResult<(), NumericTypes> { // println!( // "Inserting {:?} into {:?}, is_root_node = {is_root_node}", // node.operator(), @@ -695,11 +749,11 @@ impl Node { } } -fn collapse_root_stack_to( - root_stack: &mut Vec, - mut root: Node, - collapse_goal: &Node, -) -> EvalexprResult { +fn collapse_root_stack_to( + root_stack: &mut Vec>, + mut root: Node, + collapse_goal: &Node, +) -> EvalexprResult, NumericTypes> { loop { if let Some(mut potential_higher_root) = root_stack.pop() { // TODO I'm not sure about this >, as I have no example for different sequence operators with the same precedence @@ -720,7 +774,9 @@ fn collapse_root_stack_to( Ok(root) } -fn collapse_all_sequences(root_stack: &mut Vec) -> EvalexprResult<()> { +fn collapse_all_sequences( + root_stack: &mut Vec>, +) -> EvalexprResult<(), NumericTypes> { // println!("Collapsing all sequences"); // println!("Initial root stack is: {:?}", root_stack); let mut root = if let Some(root) = root_stack.pop() { @@ -765,7 +821,9 @@ fn collapse_all_sequences(root_stack: &mut Vec) -> EvalexprResult<()> { Ok(()) } -pub(crate) fn tokens_to_operator_tree(tokens: Vec) -> EvalexprResult { +pub(crate) fn tokens_to_operator_tree( + tokens: Vec>, +) -> EvalexprResult, NumericTypes> { let mut root_stack = vec![Node::root_node()]; let mut last_token_is_rightsided_value = false; let mut token_iter = tokens.iter().peekable(); diff --git a/src/value/display.rs b/src/value/display.rs index 599baa47..2b311a65 100644 --- a/src/value/display.rs +++ b/src/value/display.rs @@ -2,7 +2,9 @@ use std::fmt::{Display, Error, Formatter}; use crate::Value; -impl Display for Value { +use super::numeric_types::EvalexprNumericTypes; + +impl Display for Value { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match self { Value::String(string) => write!(f, "\"{}\"", string), diff --git a/src/value/mod.rs b/src/value/mod.rs index 12630de9..5e2aa3a3 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -1,17 +1,14 @@ -use crate::error::{EvalexprError, EvalexprResult}; +use crate::error::{EvalexprError, EvalexprResult, EvalexprResultValue}; use std::{convert::TryFrom, ops::RangeInclusive}; +use self::numeric_types::{DefaultNumericTypes, EvalexprNumericTypes}; + mod display; +pub mod numeric_types; pub mod value_type; -/// The type used to represent integers in `Value::Int`. -pub type IntType = i64; - -/// The type used to represent floats in `Value::Float`. -pub type FloatType = f64; - /// The type used to represent tuples in `Value::Tuple`. -pub type TupleType = Vec; +pub type TupleType = Vec>; /// The type used to represent empty values in `Value::Empty`. pub type EmptyType = (); @@ -22,23 +19,23 @@ pub const EMPTY_VALUE: () = (); /// The value type used by the parser. /// Values can be of different subtypes that are the variants of this enum. #[derive(Clone, Debug, PartialEq)] -#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] -pub enum Value { +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Value { /// A string value. String(String), /// A float value. - Float(FloatType), + Float(NumericTypes::Float), /// An integer value. - Int(IntType), + Int(NumericTypes::Int), /// A boolean value. Boolean(bool), /// A tuple value. - Tuple(TupleType), + Tuple(TupleType), /// An empty value. Empty, } -impl Value { +impl Value { /// Returns true if `self` is a `Value::String`. pub fn is_string(&self) -> bool { matches!(self, Value::String(_)) @@ -74,7 +71,7 @@ impl Value { } /// Clones the value stored in `self` as `String`, or returns `Err` if `self` is not a `Value::String`. - pub fn as_string(&self) -> EvalexprResult { + pub fn as_string(&self) -> EvalexprResult { match self { Value::String(string) => Ok(string.clone()), value => Err(EvalexprError::expected_string(value.clone())), @@ -82,33 +79,33 @@ impl Value { } /// Clones the value stored in `self` as `IntType`, or returns `Err` if `self` is not a `Value::Int`. - pub fn as_int(&self) -> EvalexprResult { + pub fn as_int(&self) -> EvalexprResult { match self { - Value::Int(i) => Ok(*i), + Value::Int(i) => Ok(i.clone()), value => Err(EvalexprError::expected_int(value.clone())), } } /// Clones the value stored in `self` as `FloatType`, or returns `Err` if `self` is not a `Value::Float`. - pub fn as_float(&self) -> EvalexprResult { + pub fn as_float(&self) -> EvalexprResult { match self { - Value::Float(f) => Ok(*f), + Value::Float(f) => Ok(f.clone()), value => Err(EvalexprError::expected_float(value.clone())), } } /// Clones the value stored in `self` as `FloatType`, or returns `Err` if `self` is not a `Value::Float` or `Value::Int`. /// Note that this method silently converts `IntType` to `FloatType`, if `self` is a `Value::Int`. - pub fn as_number(&self) -> EvalexprResult { + pub fn as_number(&self) -> EvalexprResult { match self { - Value::Float(f) => Ok(*f), - Value::Int(i) => Ok(*i as FloatType), + Value::Float(f) => Ok(f.clone()), + Value::Int(i) => Ok(NumericTypes::int_as_float(i)), value => Err(EvalexprError::expected_number(value.clone())), } } /// Clones the value stored in `self` as `bool`, or returns `Err` if `self` is not a `Value::Boolean`. - pub fn as_boolean(&self) -> EvalexprResult { + pub fn as_boolean(&self) -> EvalexprResult { match self { Value::Boolean(boolean) => Ok(*boolean), value => Err(EvalexprError::expected_boolean(value.clone())), @@ -116,7 +113,7 @@ impl Value { } /// Clones the value stored in `self` as `TupleType`, or returns `Err` if `self` is not a `Value::Tuple`. - pub fn as_tuple(&self) -> EvalexprResult { + pub fn as_tuple(&self) -> EvalexprResult, NumericTypes> { match self { Value::Tuple(tuple) => Ok(tuple.clone()), value => Err(EvalexprError::expected_tuple(value.clone())), @@ -124,7 +121,10 @@ impl Value { } /// Clones the value stored in `self` as `TupleType` or returns `Err` if `self` is not a `Value::Tuple` of the required length. - pub fn as_fixed_len_tuple(&self, len: usize) -> EvalexprResult { + pub fn as_fixed_len_tuple( + &self, + len: usize, + ) -> EvalexprResult, NumericTypes> { match self { Value::Tuple(tuple) => { if tuple.len() == len { @@ -138,7 +138,10 @@ impl Value { } /// Clones the value stored in `self` as `TupleType` or returns `Err` if `self` is not a `Value::Tuple` with length in the required range. - pub fn as_ranged_len_tuple(&self, range: RangeInclusive) -> EvalexprResult { + pub fn as_ranged_len_tuple( + &self, + range: RangeInclusive, + ) -> EvalexprResult, NumericTypes> { match self { Value::Tuple(tuple) => { if range.contains(&tuple.len()) { @@ -155,7 +158,7 @@ impl Value { } /// Returns `()`, or returns`Err` if `self` is not a `Value::Tuple`. - pub fn as_empty(&self) -> EvalexprResult<()> { + pub fn as_empty(&self) -> EvalexprResult<(), NumericTypes> { match self { Value::Empty => Ok(()), value => Err(EvalexprError::expected_empty(value.clone())), @@ -173,60 +176,60 @@ impl Value { Value::Empty => String::from("()"), } } -} -impl From for Value { - fn from(string: String) -> Self { - Value::String(string) + /// Create a new `Value` from its corresponding raw float type. + pub fn from_float(float: NumericTypes::Float) -> Self { + Self::Float(float) } -} -impl From<&str> for Value { - fn from(string: &str) -> Self { - Value::String(string.to_string()) + /// Create a new `Value` from its corresponding raw int type. + pub fn from_int(int: NumericTypes::Int) -> Self { + Self::Int(int) } } -impl From for Value { - fn from(float: FloatType) -> Self { - Value::Float(float) +impl From for Value { + fn from(string: String) -> Self { + Value::String(string) } } -impl From for Value { - fn from(int: IntType) -> Self { - Value::Int(int) +impl From<&str> for Value { + fn from(string: &str) -> Self { + Value::String(string.to_string()) } } -impl From for Value { +impl From for Value { fn from(boolean: bool) -> Self { Value::Boolean(boolean) } } -impl From for Value { - fn from(tuple: TupleType) -> Self { +impl From> for Value { + fn from(tuple: TupleType) -> Self { Value::Tuple(tuple) } } -impl From for EvalexprResult { - fn from(value: Value) -> Self { +impl From> + for EvalexprResultValue +{ + fn from(value: Value) -> Self { Ok(value) } } -impl From<()> for Value { +impl From<()> for Value { fn from(_: ()) -> Self { Value::Empty } } -impl TryFrom for String { - type Error = EvalexprError; +impl TryFrom> for String { + type Error = EvalexprError; - fn try_from(value: Value) -> Result { + fn try_from(value: Value) -> Result { if let Value::String(value) = value { Ok(value) } else { @@ -235,34 +238,10 @@ impl TryFrom for String { } } -impl TryFrom for FloatType { - type Error = EvalexprError; +impl TryFrom> for bool { + type Error = EvalexprError; - fn try_from(value: Value) -> Result { - if let Value::Float(value) = value { - Ok(value) - } else { - Err(EvalexprError::ExpectedFloat { actual: value }) - } - } -} - -impl TryFrom for IntType { - type Error = EvalexprError; - - fn try_from(value: Value) -> Result { - if let Value::Int(value) = value { - Ok(value) - } else { - Err(EvalexprError::ExpectedInt { actual: value }) - } - } -} - -impl TryFrom for bool { - type Error = EvalexprError; - - fn try_from(value: Value) -> Result { + fn try_from(value: Value) -> Result { if let Value::Boolean(value) = value { Ok(value) } else { @@ -271,10 +250,10 @@ impl TryFrom for bool { } } -impl TryFrom for TupleType { - type Error = EvalexprError; +impl TryFrom> for TupleType { + type Error = EvalexprError; - fn try_from(value: Value) -> Result { + fn try_from(value: Value) -> Result { if let Value::Tuple(value) = value { Ok(value) } else { @@ -283,10 +262,10 @@ impl TryFrom for TupleType { } } -impl TryFrom for () { - type Error = EvalexprError; +impl TryFrom> for () { + type Error = EvalexprError; - fn try_from(value: Value) -> Result { + fn try_from(value: Value) -> Result { if let Value::Empty = value { Ok(()) } else { @@ -297,47 +276,62 @@ impl TryFrom for () { #[cfg(test)] mod tests { - use crate::value::{TupleType, Value}; + use crate::value::{numeric_types::DefaultNumericTypes, TupleType, Value}; #[test] fn test_value_conversions() { assert_eq!( - Value::from("string").as_string(), + Value::::from("string").as_string(), Ok(String::from("string")) ); - assert_eq!(Value::from(3).as_int(), Ok(3)); - assert_eq!(Value::from(3.3).as_float(), Ok(3.3)); - assert_eq!(Value::from(true).as_boolean(), Ok(true)); + assert_eq!(Value::::from_int(3).as_int(), Ok(3)); assert_eq!( - Value::from(TupleType::new()).as_tuple(), + Value::::from_float(3.3).as_float(), + Ok(3.3) + ); + assert_eq!( + Value::::from(true).as_boolean(), + Ok(true) + ); + assert_eq!( + Value::::from(TupleType::new()).as_tuple(), Ok(TupleType::new()) ); } #[test] fn test_value_checks() { - assert!(Value::from("string").is_string()); - assert!(Value::from(3).is_int()); - assert!(Value::from(3.3).is_float()); - assert!(Value::from(true).is_boolean()); - assert!(Value::from(TupleType::new()).is_tuple()); + assert!(Value::::from("string").is_string()); + assert!(Value::::from_int(3).is_int()); + assert!(Value::::from_float(3.3).is_float()); + assert!(Value::::from(true).is_boolean()); + assert!(Value::::from(TupleType::new()).is_tuple()); } #[test] fn test_value_str_from() { - assert_eq!(Value::from("string").str_from(), "string"); - assert_eq!(Value::from(3.3).str_from(), "3.3"); - assert_eq!(Value::from(3).str_from(), "3"); - assert_eq!(Value::from(true).str_from(), "true"); - assert_eq!(Value::from(()).str_from(), "()"); assert_eq!( - Value::from(TupleType::from([ - Value::from("string"), - Value::from(3.3), - Value::from(3), - Value::from(TupleType::from([Value::from(42), Value::from(4.2),])), - Value::from(()), - Value::from(true), + Value::::from("string").str_from(), + "string" + ); + assert_eq!( + Value::::from_float(3.3).str_from(), + "3.3" + ); + assert_eq!(Value::::from_int(3).str_from(), "3"); + assert_eq!(Value::::from(true).str_from(), "true"); + assert_eq!(Value::::from(()).str_from(), "()"); + assert_eq!( + Value::::from(TupleType::from([ + Value::::from("string"), + Value::::from_float(3.3), + Value::::from_int(3), + Value::::from(TupleType::from([ + Value::::from_int(42), + Value::::from_float(4.2), + ])), + Value::::from(()), + Value::::from(true), ])) .str_from(), r#"("string", 3.3, 3, (42, 4.2), (), true)"# diff --git a/src/value/numeric_types.rs b/src/value/numeric_types.rs new file mode 100644 index 00000000..1da4c11c --- /dev/null +++ b/src/value/numeric_types.rs @@ -0,0 +1,515 @@ +use std::{ + convert::TryInto, + fmt::{Debug, Display}, + ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Not, Rem, Shl, Shr, Sub}, + str::FromStr, +}; + +use crate::{EvalexprError, EvalexprResult, Value}; + +/// A trait to parameterise `evalexpr` with an int type and a float type. +/// +/// See [`EvalexprInt`] and [`EvalexprFloat`] for the requirements on the types. +pub trait EvalexprNumericTypes: 'static + Sized + Debug + Clone + PartialEq { + /// The integer type. + #[cfg(feature = "serde")] + type Int: EvalexprInt + serde::Serialize + for<'de> serde::Deserialize<'de>; + + /// The integer type. + #[cfg(not(feature = "serde"))] + type Int: EvalexprInt; + + /// The float type. + #[cfg(feature = "serde")] + type Float: EvalexprFloat + serde::Serialize + for<'de> serde::Deserialize<'de>; + + /// The float type. + #[cfg(not(feature = "serde"))] + type Float: EvalexprFloat; + + /// Convert an integer to a float using the `as` operator or a similar mechanic. + fn int_as_float(int: &Self::Int) -> Self::Float; + + /// Convert a float to an integer using the `as` operator or a similar mechanic. + fn float_as_int(float: &Self::Float) -> Self::Int; +} + +/// An integer type that can be used by `evalexpr`. +pub trait EvalexprInt>: + Clone + Debug + Display + FromStr + Eq + Ord +{ + /// The minimum value of the integer type. + const MIN: Self; + + /// The maximum value of the integer type. + const MAX: Self; + + /// Convert a value of type [`usize`] into `Self`. + fn from_usize(int: usize) -> EvalexprResult; + + /// Convert `self` into [`usize`]. + #[expect(clippy::wrong_self_convention)] + fn into_usize(&self) -> EvalexprResult; + + /// Parse `Self` from a hex string. + #[expect(clippy::result_unit_err)] + fn from_hex_str(literal: &str) -> Result; + + /// Perform an addition operation, returning an error on overflow. + fn checked_add(&self, rhs: &Self) -> EvalexprResult; + + /// Perform a subtraction operation, returning an error on overflow. + fn checked_sub(&self, rhs: &Self) -> EvalexprResult; + + /// Perform a negation operation, returning an error on overflow. + fn checked_neg(&self) -> EvalexprResult; + + /// Perform a multiplication operation, returning an error on overflow. + fn checked_mul(&self, rhs: &Self) -> EvalexprResult; + + /// Perform a division operation, returning an error on overflow. + fn checked_div(&self, rhs: &Self) -> EvalexprResult; + + /// Perform a remainder operation, returning an error on overflow. + fn checked_rem(&self, rhs: &Self) -> EvalexprResult; + + /// Compute the absolute value, returning an error on overflow. + fn abs(&self) -> EvalexprResult; + + /// Perform a bitand operation. + fn bitand(&self, rhs: &Self) -> Self; + + /// Perform a bitor operation. + fn bitor(&self, rhs: &Self) -> Self; + + /// Perform a bitxor operation. + fn bitxor(&self, rhs: &Self) -> Self; + + /// Perform a bitnot operation. + fn bitnot(&self) -> Self; + + /// Perform a shl operation. + fn bit_shift_left(&self, rhs: &Self) -> Self; + + /// Perform a shr operation. + fn bit_shift_right(&self, rhs: &Self) -> Self; +} + +/// A float type that can be used by `evalexpr`. +pub trait EvalexprFloat>: + Clone + + Debug + + Display + + FromStr + + PartialEq + + PartialOrd + + Add + + Sub + + Neg + + Mul + + Div + + Rem +{ + /// The smallest non-NaN floating point value. + /// + /// Typically, this is negative infinity. + const MIN: Self; + + /// The largest non-NaN floating point value. + /// + /// Typically, this is positive infinity. + const MAX: Self; + + /// Perform a power operation. + fn pow(&self, exponent: &Self) -> Self; + + /// Compute the natural logarithm. + fn ln(&self) -> Self; + + /// Compute the logarithm to a certain base. + fn log(&self, base: &Self) -> Self; + + /// Compute the logarithm base 2. + fn log2(&self) -> Self; + + /// Compute the logarithm base 10. + fn log10(&self) -> Self; + + /// Exponentiate with base `e`. + fn exp(&self) -> Self; + + /// Exponentiate with base 2. + fn exp2(&self) -> Self; + + /// Compute the cosine. + fn cos(&self) -> Self; + + /// Compute the hyperbolic cosine. + fn cosh(&self) -> Self; + + /// Compute the arccosine. + fn acos(&self) -> Self; + + /// Compute the hyperbolic arccosine. + fn acosh(&self) -> Self; + + /// Compute the sine. + fn sin(&self) -> Self; + + /// Compute the hyperbolic sine. + fn sinh(&self) -> Self; + + /// Compute the arcsine. + fn asin(&self) -> Self; + + /// Compute the hyperbolic arcsine. + fn asinh(&self) -> Self; + + /// Compute the tangent. + fn tan(&self) -> Self; + + /// Compute the hyperbolic tangent. + fn tanh(&self) -> Self; + + /// Compute the arctangent. + fn atan(&self) -> Self; + + /// Compute the hyperbolic arctangent. + fn atanh(&self) -> Self; + + /// Compute the four quadrant arctangent. + fn atan2(&self, x: &Self) -> Self; + + /// Compute the square root. + fn sqrt(&self) -> Self; + + /// Compute the cubic root. + fn cbrt(&self) -> Self; + + /// Compute the distance between the origin and a point (`self`, `other`) on the Euclidean plane. + fn hypot(&self, other: &Self) -> Self; + + /// Compute the largest integer less than or equal to `self`. + fn floor(&self) -> Self; + + /// Returns the nearest integer to `self`. If a value is half-way between two integers, round away from `0.0`. + fn round(&self) -> Self; + + /// Compute the largest integer greater than or equal to `self`. + fn ceil(&self) -> Self; + + /// Returns true if `self` is not a number. + fn is_nan(&self) -> bool; + + /// Returns true if `self` is finite. + fn is_finite(&self) -> bool; + + /// Returns true if `self` is infinite. + fn is_infinite(&self) -> bool; + + /// Returns true if `self` is normal. + fn is_normal(&self) -> bool; + + /// Returns the absolute value of self. + fn abs(&self) -> Self; + + /// Returns the minimum of the two numbers, ignoring NaN. + fn min(&self, other: &Self) -> Self; + + /// Returns the maximum of the two numbers, ignoring NaN. + fn max(&self, other: &Self) -> Self; + + /// Generate a random float value between 0.0 and 1.0. + /// + /// If the feature `rand` is not enabled, then this method always returns [`EvalexprError::RandNotEnabled`]. + fn random() -> EvalexprResult; +} + +/// See [`EvalexprNumericTypes`]. +/// +/// This empty struct uses [`i64`] as its integer type and [`f64`] as its float type. +#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct DefaultNumericTypes; + +impl EvalexprNumericTypes for DefaultNumericTypes { + type Int = i64; + type Float = f64; + + fn int_as_float(int: &Self::Int) -> Self::Float { + *int as Self::Float + } + + fn float_as_int(float: &Self::Float) -> Self::Int { + *float as Self::Int + } +} + +impl> EvalexprInt for i64 { + const MIN: Self = Self::MIN; + const MAX: Self = Self::MAX; + + fn from_usize(int: usize) -> EvalexprResult { + int.try_into() + .map_err(|_| EvalexprError::IntFromUsize { usize_int: int }) + } + + fn into_usize(&self) -> EvalexprResult { + if *self >= 0 { + (*self as u64) + .try_into() + .map_err(|_| EvalexprError::IntIntoUsize { int: *self }) + } else { + Err(EvalexprError::IntIntoUsize { int: *self }) + } + } + + fn from_hex_str(literal: &str) -> Result { + Self::from_str_radix(literal, 16).map_err(|_| ()) + } + + fn checked_add(&self, rhs: &Self) -> EvalexprResult { + let result = (*self).checked_add(*rhs); + if let Some(result) = result { + Ok(result) + } else { + Err(EvalexprError::addition_error( + Value::::from_int(*self), + Value::::from_int(*rhs), + )) + } + } + + fn checked_sub(&self, rhs: &Self) -> EvalexprResult { + let result = (*self).checked_sub(*rhs); + if let Some(result) = result { + Ok(result) + } else { + Err(EvalexprError::subtraction_error( + Value::::from_int(*self), + Value::::from_int(*rhs), + )) + } + } + + fn checked_neg(&self) -> EvalexprResult { + let result = (*self).checked_neg(); + if let Some(result) = result { + Ok(result) + } else { + Err(EvalexprError::negation_error( + Value::::from_int(*self), + )) + } + } + + fn checked_mul(&self, rhs: &Self) -> EvalexprResult { + let result = (*self).checked_mul(*rhs); + if let Some(result) = result { + Ok(result) + } else { + Err(EvalexprError::multiplication_error( + Value::::from_int(*self), + Value::::from_int(*rhs), + )) + } + } + + fn checked_div(&self, rhs: &Self) -> EvalexprResult { + let result = (*self).checked_div(*rhs); + if let Some(result) = result { + Ok(result) + } else { + Err(EvalexprError::division_error( + Value::::from_int(*self), + Value::::from_int(*rhs), + )) + } + } + + fn checked_rem(&self, rhs: &Self) -> EvalexprResult { + let result = (*self).checked_rem(*rhs); + if let Some(result) = result { + Ok(result) + } else { + Err(EvalexprError::modulation_error( + Value::::from_int(*self), + Value::::from_int(*rhs), + )) + } + } + + fn abs(&self) -> EvalexprResult { + Ok((*self).abs()) + } + + fn bitand(&self, rhs: &Self) -> Self { + BitAnd::bitand(*self, *rhs) + } + + fn bitor(&self, rhs: &Self) -> Self { + BitOr::bitor(*self, *rhs) + } + + fn bitxor(&self, rhs: &Self) -> Self { + BitXor::bitxor(*self, *rhs) + } + + fn bitnot(&self) -> Self { + Not::not(*self) + } + + fn bit_shift_left(&self, rhs: &Self) -> Self { + Shl::shl(*self, *rhs) + } + + fn bit_shift_right(&self, rhs: &Self) -> Self { + Shr::shr(*self, *rhs) + } +} + +impl> EvalexprFloat for f64 { + const MIN: Self = Self::NEG_INFINITY; + const MAX: Self = Self::INFINITY; + + fn pow(&self, exponent: &Self) -> Self { + (*self).powf(*exponent) + } + + fn ln(&self) -> Self { + (*self).ln() + } + + fn log(&self, base: &Self) -> Self { + (*self).log(*base) + } + + fn log2(&self) -> Self { + (*self).log2() + } + + fn log10(&self) -> Self { + (*self).log10() + } + + fn exp(&self) -> Self { + (*self).exp() + } + + fn exp2(&self) -> Self { + (*self).exp2() + } + + fn cos(&self) -> Self { + (*self).cos() + } + + fn cosh(&self) -> Self { + (*self).cosh() + } + + fn acos(&self) -> Self { + (*self).acos() + } + + fn acosh(&self) -> Self { + (*self).acosh() + } + + fn sin(&self) -> Self { + (*self).sin() + } + + fn sinh(&self) -> Self { + (*self).sinh() + } + + fn asin(&self) -> Self { + (*self).asin() + } + + fn asinh(&self) -> Self { + (*self).asinh() + } + + fn tan(&self) -> Self { + (*self).tan() + } + + fn tanh(&self) -> Self { + (*self).tanh() + } + + fn atan(&self) -> Self { + (*self).atan() + } + + fn atanh(&self) -> Self { + (*self).atanh() + } + + fn atan2(&self, x: &Self) -> Self { + (*self).atan2(*x) + } + + fn sqrt(&self) -> Self { + (*self).sqrt() + } + + fn cbrt(&self) -> Self { + (*self).cbrt() + } + + fn hypot(&self, other: &Self) -> Self { + (*self).hypot(*other) + } + + fn floor(&self) -> Self { + (*self).floor() + } + + fn round(&self) -> Self { + (*self).round() + } + + fn ceil(&self) -> Self { + (*self).ceil() + } + + fn is_nan(&self) -> bool { + (*self).is_nan() + } + + fn is_finite(&self) -> bool { + (*self).is_finite() + } + + fn is_infinite(&self) -> bool { + (*self).is_infinite() + } + + fn is_normal(&self) -> bool { + (*self).is_normal() + } + + fn abs(&self) -> Self { + (*self).abs() + } + + fn min(&self, other: &Self) -> Self { + (*self).min(*other) + } + + fn max(&self, other: &Self) -> Self { + (*self).max(*other) + } + + fn random() -> EvalexprResult { + #[cfg(feature = "rand")] + let result = Ok(rand::random()); + + #[cfg(not(feature = "rand"))] + let result = Err(EvalexprError::RandNotEnabled); + + result + } +} diff --git a/src/value/value_type.rs b/src/value/value_type.rs index 4ea7395f..a2d86bf7 100644 --- a/src/value/value_type.rs +++ b/src/value/value_type.rs @@ -1,5 +1,7 @@ use crate::Value; +use super::numeric_types::EvalexprNumericTypes; + /// The type of a `Value`. #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum ValueType { @@ -17,8 +19,8 @@ pub enum ValueType { Empty, } -impl From<&Value> for ValueType { - fn from(value: &Value) -> Self { +impl From<&Value> for ValueType { + fn from(value: &Value) -> Self { match value { Value::String(_) => ValueType::String, Value::Float(_) => ValueType::Float, @@ -30,14 +32,14 @@ impl From<&Value> for ValueType { } } -impl From<&mut Value> for ValueType { - fn from(value: &mut Value) -> Self { - From::<&Value>::from(value) +impl From<&mut Value> for ValueType { + fn from(value: &mut Value) -> Self { + From::<&Value>::from(value) } } -impl From<&&mut Value> for ValueType { - fn from(value: &&mut Value) -> Self { - From::<&Value>::from(*value) +impl From<&&mut Value> for ValueType { + fn from(value: &&mut Value) -> Self { + From::<&Value>::from(*value) } } diff --git a/tests/integration.rs b/tests/integration.rs index 2cbb433e..977f293b 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -91,7 +91,9 @@ fn test_pow_examples() { assert_eq!(eval("1 ^ 4"), Ok(Value::Float(1.0))); assert_eq!( eval("6 ^ 4"), - Ok(Value::Float((6.0 as FloatType).powf(4.0))) + Ok(Value::Float( + (6.0 as ::Float).powf(4.0) + )) ); assert_eq!(eval("1 ^ 4 + 2"), Ok(Value::Float(3.0))); assert_eq!(eval("2 ^ (4 + 2)"), Ok(Value::Float(64.0))); @@ -110,7 +112,7 @@ fn test_boolean_examples() { #[test] fn test_with_context() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); context .set_value("tr".into(), Value::Boolean(true)) .unwrap(); @@ -144,7 +146,7 @@ fn test_with_context() { #[test] fn test_functions() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); context .set_function( "sub2".to_string(), @@ -175,7 +177,7 @@ fn test_functions() { #[test] fn test_n_ary_functions() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); context .set_function( "sub2".into(), @@ -234,9 +236,11 @@ fn test_n_ary_functions() { .set_function( "count".into(), Function::new(|arguments| match arguments { - Value::Tuple(tuple) => Ok(Value::from(tuple.len() as IntType)), - Value::Empty => Ok(Value::from(0)), - _ => Ok(Value::from(1)), + Value::Tuple(tuple) => Ok(Value::from_int( + tuple.len() as ::Int + )), + Value::Empty => Ok(Value::from_int(0)), + _ => Ok(Value::from_int(1)), }), ) .unwrap(); @@ -282,7 +286,7 @@ fn test_n_ary_functions() { #[test] fn test_capturing_functions() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); // this variable is captured by the function let three = 3; context @@ -292,7 +296,9 @@ fn test_capturing_functions() { if let Value::Int(int) = argument { Ok(Value::Int(int * three)) } else if let Value::Float(float) = argument { - Ok(Value::Float(float * three as FloatType)) + Ok(Value::Float( + float * three as ::Float, + )) } else { Err(EvalexprError::expected_number(argument.clone())) } @@ -326,15 +332,21 @@ fn test_builtin_functions() { // Powers assert_eq!( eval("math::exp(2)"), - Ok(Value::Float((2.0 as FloatType).exp())) + Ok(Value::Float( + (2.0 as ::Float).exp() + )) ); assert_eq!( eval("math::exp2(2)"), - Ok(Value::Float((2.0 as FloatType).exp2())) + Ok(Value::Float( + (2.0 as ::Float).exp2() + )) ); assert_eq!( eval("math::pow(1.5, 1.3)"), - Ok(Value::Float((1.5 as FloatType).powf(1.3))) + Ok(Value::Float( + (1.5 as ::Float).powf(1.3) + )) ); // Cos assert_eq!(eval("math::cos(0)"), Ok(Value::Float(1.0))); @@ -353,7 +365,9 @@ fn test_builtin_functions() { assert_eq!(eval("math::atanh(0)"), Ok(Value::Float(0.0))); assert_eq!( eval("math::atan2(1.2, -5.5)"), - Ok(Value::Float((1.2 as FloatType).atan2(-5.5))) + Ok(Value::Float( + (1.2 as ::Float).atan2(-5.5) + )) ); // Root assert_eq!(eval("math::sqrt(25)"), Ok(Value::Float(5.0))); @@ -361,7 +375,9 @@ fn test_builtin_functions() { // Hypotenuse assert_eq!( eval("math::hypot(8.2, 1.1)"), - Ok(Value::Float((8.2 as FloatType).hypot(1.1))) + Ok(Value::Float( + (8.2 as ::Float).hypot(1.1) + )) ); // Rounding assert_eq!(eval("floor(1.1)"), Ok(Value::Float(1.0))); @@ -595,13 +611,47 @@ fn test_errors() { #[test] fn test_no_panic() { - assert!(eval(&format!("{} + {}", IntType::MAX, IntType::MAX)).is_err()); - assert!(eval(&format!("-{} - {}", IntType::MAX, IntType::MAX)).is_err()); - assert!(eval(&format!("-(-{} - 1)", IntType::MAX)).is_err()); - assert!(eval(&format!("{} * {}", IntType::MAX, IntType::MAX)).is_err()); - assert!(eval(&format!("{} / {}", IntType::MAX, 0)).is_err()); - assert!(eval(&format!("{} % {}", IntType::MAX, 0)).is_err()); - assert!(eval(&format!("{} ^ {}", IntType::MAX, IntType::MAX)).is_ok()); + assert!(eval(&format!( + "{} + {}", + ::Int::MAX, + ::Int::MAX + )) + .is_err()); + assert!(eval(&format!( + "-{} - {}", + ::Int::MAX, + ::Int::MAX + )) + .is_err()); + assert!(eval(&format!( + "-(-{} - 1)", + ::Int::MAX + )) + .is_err()); + assert!(eval(&format!( + "{} * {}", + ::Int::MAX, + ::Int::MAX + )) + .is_err()); + assert!(eval(&format!( + "{} / {}", + ::Int::MAX, + 0 + )) + .is_err()); + assert!(eval(&format!( + "{} % {}", + ::Int::MAX, + 0 + )) + .is_err()); + assert!(eval(&format!( + "{} ^ {}", + ::Int::MAX, + ::Int::MAX + )) + .is_ok()); assert!(eval("if").is_err()); assert!(eval("if()").is_err()); assert!(eval("if(true, 1)").is_err()); @@ -612,7 +662,7 @@ fn test_no_panic() { #[test] fn test_shortcut_functions() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); context .set_value("string".into(), Value::from("a string")) .unwrap(); @@ -890,17 +940,23 @@ fn test_shortcut_functions() { // With detour via build_operator_tree assert_eq!( - build_operator_tree("\"3.3\"").unwrap().eval_string(), + build_operator_tree::("\"3.3\"") + .unwrap() + .eval_string(), Ok("3.3".to_owned()) ); assert_eq!( - build_operator_tree("3.3").unwrap().eval_string(), + build_operator_tree::("3.3") + .unwrap() + .eval_string(), Err(EvalexprError::ExpectedString { actual: Value::Float(3.3) }) ); assert_eq!( - build_operator_tree("3..3").unwrap().eval_string(), + build_operator_tree::("3..3") + .unwrap() + .eval_string(), Err(EvalexprError::VariableIdentifierNotFound("3..3".to_owned())) ); assert_eq!( @@ -944,15 +1000,24 @@ fn test_shortcut_functions() { Err(EvalexprError::VariableIdentifierNotFound("3..3".to_owned())) ); - assert_eq!(build_operator_tree("3.3").unwrap().eval_float(), Ok(3.3)); assert_eq!( - build_operator_tree("33").unwrap().eval_float(), + build_operator_tree::("3.3") + .unwrap() + .eval_float(), + Ok(3.3) + ); + assert_eq!( + build_operator_tree::("33") + .unwrap() + .eval_float(), Err(EvalexprError::ExpectedFloat { actual: Value::Int(33) }) ); assert_eq!( - build_operator_tree("asd()").unwrap().eval_float(), + build_operator_tree::("asd()") + .unwrap() + .eval_float(), Err(EvalexprError::FunctionIdentifierNotFound("asd".to_owned())) ); assert_eq!( @@ -996,15 +1061,24 @@ fn test_shortcut_functions() { Err(EvalexprError::VariableIdentifierNotFound("asd".to_owned())) ); - assert_eq!(build_operator_tree("3").unwrap().eval_int(), Ok(3)); assert_eq!( - build_operator_tree("3.3").unwrap().eval_int(), + build_operator_tree::("3") + .unwrap() + .eval_int(), + Ok(3) + ); + assert_eq!( + build_operator_tree::("3.3") + .unwrap() + .eval_int(), Err(EvalexprError::ExpectedInt { actual: Value::Float(3.3) }) ); assert_eq!( - build_operator_tree("(,);.").unwrap().eval_int(), + build_operator_tree::("(,);.") + .unwrap() + .eval_int(), Err(EvalexprError::VariableIdentifierNotFound(".".to_owned())) ); assert_eq!( @@ -1048,15 +1122,24 @@ fn test_shortcut_functions() { Err(EvalexprError::VariableIdentifierNotFound(".".to_owned())) ); - assert_eq!(build_operator_tree("3").unwrap().eval_number(), Ok(3.0)); assert_eq!( - build_operator_tree("true").unwrap().eval_number(), + build_operator_tree::("3") + .unwrap() + .eval_number(), + Ok(3.0) + ); + assert_eq!( + build_operator_tree::("true") + .unwrap() + .eval_number(), Err(EvalexprError::ExpectedNumber { actual: Value::Boolean(true) }) ); assert_eq!( - build_operator_tree("abc").unwrap().eval_number(), + build_operator_tree::("abc") + .unwrap() + .eval_number(), Err(EvalexprError::VariableIdentifierNotFound("abc".to_owned())) ); assert_eq!( @@ -1101,17 +1184,23 @@ fn test_shortcut_functions() { ); assert_eq!( - build_operator_tree("true").unwrap().eval_boolean(), + build_operator_tree::("true") + .unwrap() + .eval_boolean(), Ok(true) ); assert_eq!( - build_operator_tree("4").unwrap().eval_boolean(), + build_operator_tree::("4") + .unwrap() + .eval_boolean(), Err(EvalexprError::ExpectedBoolean { actual: Value::Int(4) }) ); assert_eq!( - build_operator_tree("trueee").unwrap().eval_boolean(), + build_operator_tree::("trueee") + .unwrap() + .eval_boolean(), Err(EvalexprError::VariableIdentifierNotFound( "trueee".to_owned() )) @@ -1162,17 +1251,23 @@ fn test_shortcut_functions() { ); assert_eq!( - build_operator_tree("3,3").unwrap().eval_tuple(), + build_operator_tree::("3,3") + .unwrap() + .eval_tuple(), Ok(vec![Value::Int(3), Value::Int(3)]) ); assert_eq!( - build_operator_tree("33").unwrap().eval_tuple(), + build_operator_tree::("33") + .unwrap() + .eval_tuple(), Err(EvalexprError::ExpectedTuple { actual: Value::Int(33) }) ); assert_eq!( - build_operator_tree("3a3").unwrap().eval_tuple(), + build_operator_tree::("3a3") + .unwrap() + .eval_tuple(), Err(EvalexprError::VariableIdentifierNotFound("3a3".to_owned())) ); assert_eq!( @@ -1217,21 +1312,29 @@ fn test_shortcut_functions() { ); assert_eq!( - build_operator_tree("").unwrap().eval_empty(), + build_operator_tree::("") + .unwrap() + .eval_empty(), Ok(EMPTY_VALUE) ); assert_eq!( - build_operator_tree("()").unwrap().eval_empty(), + build_operator_tree::("()") + .unwrap() + .eval_empty(), Ok(EMPTY_VALUE) ); assert_eq!( - build_operator_tree("(,)").unwrap().eval_empty(), + build_operator_tree::("(,)") + .unwrap() + .eval_empty(), Err(EvalexprError::ExpectedEmpty { actual: Value::Tuple(vec![Value::Empty, Value::Empty]) }) ); assert_eq!( - build_operator_tree("xaq").unwrap().eval_empty(), + build_operator_tree::("xaq") + .unwrap() + .eval_empty(), Err(EvalexprError::VariableIdentifierNotFound("xaq".to_owned())) ); assert_eq!( @@ -1295,7 +1398,7 @@ fn test_whitespace() { #[test] fn test_assignment() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); assert_eq!( eval_empty_with_context_mut("int = 3", &mut context), Ok(EMPTY_VALUE) @@ -1321,7 +1424,7 @@ fn test_assignment() { assert_eq!(eval_float_with_context("float", &context), Ok(2.0)); assert_eq!( eval_tuple_with_context("tuple", &context), - Ok(vec![1.into(), 1.into()]) + Ok(vec![Value::from_int(1), Value::from_int(1)]) ); assert_eq!(eval_empty_with_context("empty", &context), Ok(EMPTY_VALUE)); assert_eq!(eval_boolean_with_context("boolean", &context), Ok(false)); @@ -1335,7 +1438,7 @@ fn test_assignment() { #[test] fn test_expression_chaining() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); assert_eq!( eval_int_with_context_mut("a = 5; a = a + 2; a", &mut context), Ok(7) @@ -1344,7 +1447,7 @@ fn test_expression_chaining() { #[test] fn test_strings() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); assert_eq!(eval("\"string\""), Ok(Value::from("string"))); assert_eq!( eval_with_context_mut("a = \"a string\"", &mut context), @@ -1381,45 +1484,56 @@ fn test_tuple_definitions() { assert_eq!(eval_int("(3)"), Ok(3)); assert_eq!( eval_tuple("(3, 4)"), - Ok(vec![Value::from(3), Value::from(4)]) + Ok(vec![Value::from_int(3), Value::from_int(4)]) ); assert_eq!( eval_tuple("2, (5, 6)"), Ok(vec![ - Value::from(2), - Value::from(vec![Value::from(5), Value::from(6)]) + Value::from_int(2), + Value::from(vec![Value::from_int(5), Value::from_int(6)]) ]) ); - assert_eq!(eval_tuple("1, 2"), Ok(vec![Value::from(1), Value::from(2)])); + assert_eq!( + eval_tuple("1, 2"), + Ok(vec![Value::from_int(1), Value::from_int(2)]) + ); assert_eq!( eval_tuple("1, 2, 3, 4"), Ok(vec![ - Value::from(1), - Value::from(2), - Value::from(3), - Value::from(4) + Value::from_int(1), + Value::from_int(2), + Value::from_int(3), + Value::from_int(4) ]) ); assert_eq!( eval_tuple("(1, 2, 3), 5, 6, (true, false, 0)"), Ok(vec![ - Value::from(vec![Value::from(1), Value::from(2), Value::from(3)]), - Value::from(5), - Value::from(6), - Value::from(vec![Value::from(true), Value::from(false), Value::from(0)]) + Value::from(vec![ + Value::from_int(1), + Value::from_int(2), + Value::from_int(3) + ]), + Value::from_int(5), + Value::from_int(6), + Value::from(vec![ + Value::from(true), + Value::from(false), + Value::from_int(0) + ]) ]) ); assert_eq!( eval_tuple("1, (2)"), - Ok(vec![Value::from(1), Value::from(2)]) + Ok(vec![Value::from_int(1), Value::from_int(2)]) ); assert_eq!( eval_tuple("1, ()"), - Ok(vec![Value::from(1), Value::from(())]) + Ok(vec![Value::from_int(1), Value::from(())]) ); assert_eq!( eval_tuple("1, ((2))"), - Ok(vec![Value::from(1), Value::from(2)]) + Ok(vec![Value::from_int(1), Value::from_int(2)]) ); } @@ -1442,7 +1556,7 @@ fn test_implicit_context() { assert_eq!(eval_empty("a = 2 + 4 * 2; b = -5 + 3 * 5;"), Ok(())); assert_eq!( eval_tuple("a = 2 + 4 * 2; b = -5 + 3 * 5; a, b + 0.5"), - Ok(vec![Value::from(10), Value::from(10.5)]) + Ok(vec![Value::from_int(10), Value::from_float(10.5)]) ); assert_eq!( eval_string("a = \"xyz\"; b = \"abc\"; c = a + b; c"), @@ -1452,7 +1566,7 @@ fn test_implicit_context() { #[test] fn test_operator_assignments() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); assert_eq!(eval_empty_with_context_mut("a = 5", &mut context), Ok(())); assert_eq!(eval_empty_with_context_mut("a += 5", &mut context), Ok(())); assert_eq!(eval_empty_with_context_mut("a -= 5", &mut context), Ok(())); @@ -1474,7 +1588,7 @@ fn test_operator_assignments() { Ok(()) ); - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); assert_eq!(eval_int_with_context_mut("a = 5; a", &mut context), Ok(5)); assert_eq!(eval_int_with_context_mut("a += 3; a", &mut context), Ok(8)); assert_eq!(eval_int_with_context_mut("a -= 5; a", &mut context), Ok(3)); @@ -1531,7 +1645,7 @@ fn test_type_errors_in_binary_operators() { #[test] fn test_empty_context() { - let mut context = EmptyContext; + let mut context = EmptyContext::::default(); assert_eq!(context.get_value("abc"), None); assert_eq!( context.call_function("abc", &Value::Empty), @@ -1552,7 +1666,7 @@ fn test_empty_context() { #[test] fn test_empty_context_with_builtin_functions() { - let mut context = EmptyContextWithBuiltinFunctions; + let mut context = EmptyContextWithBuiltinFunctions::::default(); assert_eq!(context.get_value("abc"), None); assert_eq!( context.call_function("abc", &Value::Empty), @@ -1568,7 +1682,8 @@ fn test_empty_context_with_builtin_functions() { #[test] fn test_hashmap_context_type_safety() { - let mut context = context_map! {"a" => 5, "b" => 5.0}.unwrap(); + let mut context: HashMapContext = + context_map! {"a" => int 5, "b" => float 5.0}.unwrap(); assert_eq!( eval_with_context_mut("a = 4", &mut context), Ok(Value::Empty) @@ -1654,7 +1769,7 @@ fn test_hashmap_context_type_safety() { #[test] fn test_hashmap_context_clone_debug() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); // this variable is captured by the function let three = 3; context @@ -1664,7 +1779,9 @@ fn test_hashmap_context_clone_debug() { if let Value::Int(int) = argument { Ok(Value::Int(int * three)) } else if let Value::Float(float) = argument { - Ok(Value::Float(float * three as FloatType)) + Ok(Value::Float( + float * three as ::Float, + )) } else { Err(EvalexprError::expected_number(argument.clone())) } @@ -1679,7 +1796,9 @@ fn test_hashmap_context_clone_debug() { Function::new(move |_| Ok(Value::Int(four))), ) .unwrap(); - context.set_value("variable_five".into(), 5.into()).unwrap(); + context + .set_value("variable_five".into(), Value::from_int(5)) + .unwrap(); let context = context; #[allow(clippy::redundant_clone)] let cloned_context = context.clone(); @@ -1687,7 +1806,7 @@ fn test_hashmap_context_clone_debug() { assert_eq!(format!("{:?}", &context), format!("{:?}", &cloned_context)); assert_eq!( cloned_context.get_value("variable_five"), - Some(&Value::from(5)) + Some(&Value::from_int(5)) ); assert_eq!( eval_with_context("mult_3 2", &cloned_context), @@ -1724,7 +1843,8 @@ fn test_error_constructors() { }) ); assert_eq!( - Value::Tuple(vec![Value::Int(4), Value::Int(5)]).as_fixed_len_tuple(3), + Value::Tuple(vec![Value::::Int(4), Value::Int(5)]) + .as_fixed_len_tuple(3), Err(EvalexprError::ExpectedFixedLengthTuple { expected_length: 3, actual: Value::Tuple(vec![Value::Int(4), Value::Int(5)]) @@ -1744,9 +1864,12 @@ fn test_error_constructors() { }) ); - assert_eq!(expect_function_argument_amount(2, 2), Ok(())); assert_eq!( - expect_function_argument_amount(2, 3), + expect_function_argument_amount::(2, 2), + Ok(()) + ); + assert_eq!( + expect_function_argument_amount::(2, 3), Err(EvalexprError::WrongFunctionArgumentAmount { expected: 3..=3, actual: 2 @@ -1756,7 +1879,8 @@ fn test_error_constructors() { #[test] fn test_iterators() { - let tree = build_operator_tree("writevar = 5 + 3 + fun(4) + var").unwrap(); + let tree = + build_operator_tree::("writevar = 5 + 3 + fun(4) + var").unwrap(); let mut iter = tree.iter_identifiers(); assert_eq!(iter.next(), Some("writevar")); assert_eq!(iter.next(), Some("fun")); @@ -1786,34 +1910,35 @@ fn test_same_operator_chains() { #![allow(clippy::eq_op)] assert_eq!( eval("3.0 / 3.0 / 3.0 / 3.0"), - Ok(Value::from(3.0 / 3.0 / 3.0 / 3.0)) + Ok(Value::from_float(3.0 / 3.0 / 3.0 / 3.0)) ); assert_eq!( eval("3.0 - 3.0 - 3.0 - 3.0"), - Ok(Value::from(3.0 - 3.0 - 3.0 - 3.0)) + Ok(Value::from_float(3.0 - 3.0 - 3.0 - 3.0)) ); } #[test] fn test_long_expression_i89() { - let tree = build_operator_tree( + let tree = build_operator_tree::( "x*0.2*5/4+x*2*4*1*1*1*1*1*1*1+7*math::sin(y)-z/math::sin(3.0/2.0/(1-x*4*1*1*1*1))", ) .unwrap(); let x = 0.0; - let y: FloatType = 3.0; + let y: ::Float = 3.0; let z = 4.0; let context = context_map! { - "x" => 0.0, - "y" => 3.0, - "z" => 4.0 + "x" => float 0.0, + "y" => float 3.0, + "z" => float 4.0 } .unwrap(); let expected = x * 0.2 * 5.0 / 4.0 + x * 2.0 * 4.0 * 1.0 * 1.0 * 1.0 * 1.0 * 1.0 * 1.0 * 1.0 + 7.0 * y.sin() - z / (3.0 / 2.0 / (1.0 - x * 4.0 * 1.0 * 1.0 * 1.0 * 1.0)).sin(); - let actual: FloatType = tree.eval_float_with_context(&context).unwrap(); + let actual: ::Float = + tree.eval_float_with_context(&context).unwrap(); assert!( (expected - actual).abs() < expected.abs().min(actual.abs()) * 1e-12, "expected: {}, actual: {}", @@ -1825,178 +1950,205 @@ fn test_long_expression_i89() { #[test] fn test_value_type() { assert_eq!( - ValueType::from(&Value::String(String::new())), + ValueType::from(&Value::::String(String::new())), ValueType::String ); - assert_eq!(ValueType::from(&Value::Float(0.0)), ValueType::Float); - assert_eq!(ValueType::from(&Value::Int(0)), ValueType::Int); - assert_eq!(ValueType::from(&Value::Boolean(true)), ValueType::Boolean); - assert_eq!(ValueType::from(&Value::Tuple(Vec::new())), ValueType::Tuple); - assert_eq!(ValueType::from(&Value::Empty), ValueType::Empty); + assert_eq!( + ValueType::from(&Value::::Float(0.0)), + ValueType::Float + ); + assert_eq!( + ValueType::from(&Value::::Int(0)), + ValueType::Int + ); + assert_eq!( + ValueType::from(&Value::::Boolean(true)), + ValueType::Boolean + ); + assert_eq!( + ValueType::from(&Value::::Tuple(Vec::new())), + ValueType::Tuple + ); + assert_eq!( + ValueType::from(&Value::::Empty), + ValueType::Empty + ); assert_eq!( - ValueType::from(&mut Value::String(String::new())), + ValueType::from(&mut Value::::String(String::new())), ValueType::String ); - assert_eq!(ValueType::from(&mut Value::Float(0.0)), ValueType::Float); - assert_eq!(ValueType::from(&mut Value::Int(0)), ValueType::Int); assert_eq!( - ValueType::from(&mut Value::Boolean(true)), + ValueType::from(&mut Value::::Float(0.0)), + ValueType::Float + ); + assert_eq!( + ValueType::from(&mut Value::::Int(0)), + ValueType::Int + ); + assert_eq!( + ValueType::from(&mut Value::::Boolean(true)), ValueType::Boolean ); assert_eq!( - ValueType::from(&mut Value::Tuple(Vec::new())), + ValueType::from(&mut Value::::Tuple(Vec::new())), ValueType::Tuple ); - assert_eq!(ValueType::from(&mut Value::Empty), ValueType::Empty); + assert_eq!( + ValueType::from(&mut Value::::Empty), + ValueType::Empty + ); - assert!(!Value::String(String::new()).is_number()); - assert!(Value::Float(0.0).is_number()); - assert!(Value::Int(0).is_number()); - assert!(!Value::Boolean(true).is_number()); - assert!(!Value::Tuple(Vec::new()).is_number()); - assert!(!Value::Empty.is_number()); + assert!(!Value::::String(String::new()).is_number()); + assert!(Value::::Float(0.0).is_number()); + assert!(Value::::Int(0).is_number()); + assert!(!Value::::Boolean(true).is_number()); + assert!(!Value::::Tuple(Vec::new()).is_number()); + assert!(!Value::::Empty.is_number()); - assert!(!Value::String(String::new()).is_empty()); - assert!(!Value::Float(0.0).is_empty()); - assert!(!Value::Int(0).is_empty()); - assert!(!Value::Boolean(true).is_empty()); - assert!(!Value::Tuple(Vec::new()).is_empty()); - assert!(Value::Empty.is_empty()); + assert!(!Value::::String(String::new()).is_empty()); + assert!(!Value::::Float(0.0).is_empty()); + assert!(!Value::::Int(0).is_empty()); + assert!(!Value::::Boolean(true).is_empty()); + assert!(!Value::::Tuple(Vec::new()).is_empty()); + assert!(Value::::Empty.is_empty()); assert_eq!( - Value::String(String::new()).as_float(), + Value::::String(String::new()).as_float(), Err(EvalexprError::ExpectedFloat { actual: Value::String(String::new()) }) ); - assert_eq!(Value::Float(0.0).as_float(), Ok(0.0)); + assert_eq!(Value::::Float(0.0).as_float(), Ok(0.0)); assert_eq!( - Value::Int(0).as_float(), + Value::::Int(0).as_float(), Err(EvalexprError::ExpectedFloat { actual: Value::Int(0) }) ); assert_eq!( - Value::Boolean(true).as_float(), + Value::::Boolean(true).as_float(), Err(EvalexprError::ExpectedFloat { actual: Value::Boolean(true) }) ); assert_eq!( - Value::Tuple(Vec::new()).as_float(), + Value::::Tuple(Vec::new()).as_float(), Err(EvalexprError::ExpectedFloat { actual: Value::Tuple(Vec::new()) }) ); assert_eq!( - Value::Empty.as_float(), + Value::::Empty.as_float(), Err(EvalexprError::ExpectedFloat { actual: Value::Empty }) ); assert_eq!( - Value::String(String::new()).as_tuple(), + Value::::String(String::new()).as_tuple(), Err(EvalexprError::ExpectedTuple { actual: Value::String(String::new()) }) ); assert_eq!( - Value::Float(0.0).as_tuple(), + Value::::Float(0.0).as_tuple(), Err(EvalexprError::ExpectedTuple { actual: Value::Float(0.0) }) ); assert_eq!( - Value::Int(0).as_tuple(), + Value::::Int(0).as_tuple(), Err(EvalexprError::ExpectedTuple { actual: Value::Int(0) }) ); assert_eq!( - Value::Boolean(true).as_tuple(), + Value::::Boolean(true).as_tuple(), Err(EvalexprError::ExpectedTuple { actual: Value::Boolean(true) }) ); - assert_eq!(Value::Tuple(Vec::new()).as_tuple(), Ok(Vec::new())); assert_eq!( - Value::Empty.as_tuple(), + Value::::Tuple(Vec::new()).as_tuple(), + Ok(Vec::new()) + ); + assert_eq!( + Value::::Empty.as_tuple(), Err(EvalexprError::ExpectedTuple { actual: Value::Empty }) ); assert_eq!( - Value::String(String::new()).as_fixed_len_tuple(0), + Value::::String(String::new()).as_fixed_len_tuple(0), Err(EvalexprError::ExpectedTuple { actual: Value::String(String::new()) }) ); assert_eq!( - Value::Float(0.0).as_fixed_len_tuple(0), + Value::::Float(0.0).as_fixed_len_tuple(0), Err(EvalexprError::ExpectedTuple { actual: Value::Float(0.0) }) ); assert_eq!( - Value::Int(0).as_fixed_len_tuple(0), + Value::::Int(0).as_fixed_len_tuple(0), Err(EvalexprError::ExpectedTuple { actual: Value::Int(0) }) ); assert_eq!( - Value::Boolean(true).as_fixed_len_tuple(0), + Value::::Boolean(true).as_fixed_len_tuple(0), Err(EvalexprError::ExpectedTuple { actual: Value::Boolean(true) }) ); assert_eq!( - Value::Tuple(Vec::new()).as_fixed_len_tuple(0), + Value::::Tuple(Vec::new()).as_fixed_len_tuple(0), Ok(Vec::new()) ); assert_eq!( - Value::Empty.as_fixed_len_tuple(0), + Value::::Empty.as_fixed_len_tuple(0), Err(EvalexprError::ExpectedTuple { actual: Value::Empty }) ); assert_eq!( - Value::String(String::new()).as_empty(), + Value::::String(String::new()).as_empty(), Err(EvalexprError::ExpectedEmpty { actual: Value::String(String::new()) }) ); assert_eq!( - Value::Float(0.0).as_empty(), + Value::::Float(0.0).as_empty(), Err(EvalexprError::ExpectedEmpty { actual: Value::Float(0.0) }) ); assert_eq!( - Value::Int(0).as_empty(), + Value::::Int(0).as_empty(), Err(EvalexprError::ExpectedEmpty { actual: Value::Int(0) }) ); assert_eq!( - Value::Boolean(true).as_empty(), + Value::::Boolean(true).as_empty(), Err(EvalexprError::ExpectedEmpty { actual: Value::Boolean(true) }) ); assert_eq!( - Value::Tuple(Vec::new()).as_empty(), + Value::::Tuple(Vec::new()).as_empty(), Err(EvalexprError::ExpectedEmpty { actual: Value::Tuple(Vec::new()) }) ); - assert_eq!(Value::Empty.as_empty(), Ok(())); + assert_eq!(Value::::Empty.as_empty(), Ok(())); assert_eq!( - Result::from(Value::String(String::new())), + Result::from(Value::::String(String::new())), Ok(Value::String(String::new())) ); } @@ -2021,8 +2173,8 @@ fn test_parenthese_combinations() { Err(EvalexprError::MissingOperatorOutsideOfBrace) ); assert_eq!( - eval_with_context("a+100(a*2)", &context_map! {"a" => 4}.unwrap()), - Err(EvalexprError::MissingOperatorOutsideOfBrace) + eval_with_context("a+100(a*2)", &context_map! {"a" => int 4}.unwrap()), + Err(EvalexprError::::MissingOperatorOutsideOfBrace) ); assert_eq!(eval_int("(((1+2)*(3+4)+(5-(6)))/((7-8)))"), Ok(-20)); assert_eq!(eval_int("(((((5)))))"), Ok(5)); @@ -2032,20 +2184,8 @@ fn test_parenthese_combinations() { fn test_try_from() { #![allow(clippy::redundant_clone)] - let value = Value::String("abc".to_string()); + let value = Value::::String("abc".to_string()); assert_eq!(String::try_from(value.clone()), Ok("abc".to_string())); - assert_eq!( - FloatType::try_from(value.clone()), - Err(EvalexprError::ExpectedFloat { - actual: value.clone() - }) - ); - assert_eq!( - IntType::try_from(value.clone()), - Err(EvalexprError::ExpectedInt { - actual: value.clone() - }) - ); assert_eq!( bool::try_from(value.clone()), Err(EvalexprError::ExpectedBoolean { @@ -2065,20 +2205,13 @@ fn test_try_from() { }) ); - let value = Value::Float(1.3); + let value = Value::::Float(1.3); assert_eq!( String::try_from(value.clone()), Err(EvalexprError::ExpectedString { actual: value.clone() }) ); - assert_eq!(FloatType::try_from(value.clone()), Ok(1.3)); - assert_eq!( - IntType::try_from(value.clone()), - Err(EvalexprError::ExpectedInt { - actual: value.clone() - }) - ); assert_eq!( bool::try_from(value.clone()), Err(EvalexprError::ExpectedBoolean { @@ -2098,20 +2231,13 @@ fn test_try_from() { }) ); - let value = Value::Int(13); + let value = Value::::Int(13); assert_eq!( String::try_from(value.clone()), Err(EvalexprError::ExpectedString { actual: value.clone() }) ); - assert_eq!( - FloatType::try_from(value.clone()), - Err(EvalexprError::ExpectedFloat { - actual: value.clone() - }) - ); - assert_eq!(IntType::try_from(value.clone()), Ok(13)); assert_eq!( bool::try_from(value.clone()), Err(EvalexprError::ExpectedBoolean { @@ -2131,25 +2257,13 @@ fn test_try_from() { }) ); - let value = Value::Boolean(true); + let value = Value::::Boolean(true); assert_eq!( String::try_from(value.clone()), Err(EvalexprError::ExpectedString { actual: value.clone() }) ); - assert_eq!( - FloatType::try_from(value.clone()), - Err(EvalexprError::ExpectedFloat { - actual: value.clone() - }) - ); - assert_eq!( - IntType::try_from(value.clone()), - Err(EvalexprError::ExpectedInt { - actual: value.clone() - }) - ); assert_eq!(bool::try_from(value.clone()), Ok(true)); assert_eq!( TupleType::try_from(value.clone()), @@ -2164,25 +2278,14 @@ fn test_try_from() { }) ); - let value = Value::Tuple(vec![Value::Int(1), Value::String("abc".to_string())]); + let value = + Value::::Tuple(vec![Value::Int(1), Value::String("abc".to_string())]); assert_eq!( String::try_from(value.clone()), Err(EvalexprError::ExpectedString { actual: value.clone() }) ); - assert_eq!( - FloatType::try_from(value.clone()), - Err(EvalexprError::ExpectedFloat { - actual: value.clone() - }) - ); - assert_eq!( - IntType::try_from(value.clone()), - Err(EvalexprError::ExpectedInt { - actual: value.clone() - }) - ); assert_eq!( bool::try_from(value.clone()), Err(EvalexprError::ExpectedBoolean { @@ -2200,25 +2303,13 @@ fn test_try_from() { }) ); - let value = Value::Empty; + let value = Value::::Empty; assert_eq!( String::try_from(value.clone()), Err(EvalexprError::ExpectedString { actual: value.clone() }) ); - assert_eq!( - FloatType::try_from(value.clone()), - Err(EvalexprError::ExpectedFloat { - actual: value.clone() - }) - ); - assert_eq!( - IntType::try_from(value.clone()), - Err(EvalexprError::ExpectedInt { - actual: value.clone() - }) - ); assert_eq!( bool::try_from(value.clone()), Err(EvalexprError::ExpectedBoolean { @@ -2239,7 +2330,7 @@ fn assignment_lhs_is_identifier() { let tree = build_operator_tree("a = 1").unwrap(); let operators: Vec<_> = tree.iter().map(|node| node.operator().clone()).collect(); - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); tree.eval_with_context_mut(&mut context).unwrap(); assert_eq!(context.get_value("a"), Some(&Value::Int(1))); @@ -2261,14 +2352,17 @@ fn assignment_lhs_is_identifier() { #[test] fn test_variable_assignment_and_iteration() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); eval_with_context_mut("a = 5; b = 5.0", &mut context).unwrap(); let mut variables: Vec<_> = context.iter_variables().collect(); variables.sort_unstable_by(|(name_a, _), (name_b, _)| name_a.cmp(name_b)); assert_eq!( variables, - vec![("a".to_string(), 5.into()), ("b".to_string(), 5.0.into())], + vec![ + ("a".to_string(), Value::from_int(5)), + ("b".to_string(), Value::from_float(5.0)) + ], ); let mut variables: Vec<_> = context.iter_variable_names().collect(); @@ -2278,7 +2372,10 @@ fn test_variable_assignment_and_iteration() { #[test] fn test_negative_power() { - println!("{:?}", build_operator_tree("3^-2").unwrap()); + println!( + "{:?}", + build_operator_tree::("3^-2").unwrap() + ); assert_eq!(eval("3^-2"), Ok(Value::Float(1.0 / 9.0))); assert_eq!(eval("3^(-2)"), Ok(Value::Float(1.0 / 9.0))); assert_eq!(eval("-3^2"), Ok(Value::Float(-9.0))); @@ -2289,9 +2386,12 @@ fn test_negative_power() { #[test] fn test_builtin_functions_context() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); // Builtin functions are enabled by default for HashMapContext. - assert_eq!(eval_with_context("max(1,3)", &context), Ok(Value::from(3))); + assert_eq!( + eval_with_context("max(1,3)", &context), + Ok(Value::from_int(3)) + ); // Disabling builtin function in Context. context.set_builtin_functions_disabled(true).unwrap(); // Builtin functions are disabled and using them returns an error. @@ -2357,7 +2457,7 @@ fn test_comments() { #[test] fn test_clear() { - let mut context = HashMapContext::new(); + let mut context = HashMapContext::::new(); context.set_value("abc".into(), "def".into()).unwrap(); assert_eq!(context.get_value("abc"), Some(&("def".into()))); context.clear_functions(); @@ -2383,7 +2483,9 @@ fn test_clear() { context.clear_functions(); assert!(eval_with_context("abc(5)", &context).is_err()); - context.set_value("five".into(), 5.into()).unwrap(); + context + .set_value("five".into(), Value::from_int(5)) + .unwrap(); context .set_function( "abc".into(), diff --git a/tests/regex.rs b/tests/regex.rs index 5f83eb3d..b4dae126 100644 --- a/tests/regex.rs +++ b/tests/regex.rs @@ -1,5 +1,5 @@ #![cfg(not(tarpaulin_include))] -#![cfg(feature = "regex_support")] +#![cfg(feature = "regex")] use evalexpr::*;