[
  {
    "path": ".github/dependabot.yml",
    "content": "# Please see the documentation for all configuration options:\n# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates\n\nversion: 2\n\nupdates:\n  - package-ecosystem: \"cargo\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n"
  },
  {
    "path": ".github/workflows/continuous_integration.yml",
    "content": "# Based on https://github.com/actions-rs/meta/blob/master/recipes/msrv.md\n\non: [push, pull_request]\n\nname: Continuous integration\n\njobs:\n  check:\n    name: Check\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        rust:\n          - stable\n          - 1.56.0\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions-rs/toolchain@v1\n        with:\n          profile: minimal\n          toolchain: ${{ matrix.rust }}\n          override: true\n      - uses: actions-rs/cargo@v1\n        with:\n          command: check\n\n  test:\n    name: Test Suite\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        rust:\n          - stable\n          - 1.56.0\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions-rs/toolchain@v1\n        with:\n          profile: minimal\n          toolchain: ${{ matrix.rust }}\n          override: true\n      - uses: actions-rs/cargo@v1\n        with:\n          command: test\n\n  fmt:\n    name: Rustfmt\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        rust:\n          - stable\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions-rs/toolchain@v1\n        with:\n          profile: minimal\n          toolchain: ${{ matrix.rust }}\n          override: true\n      - run: rustup component add rustfmt\n      - uses: actions-rs/cargo@v1\n        with:\n          command: fmt\n          args: --all -- --check\n\n  clippy:\n    name: Clippy\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        rust:\n          - stable\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions-rs/toolchain@v1\n        with:\n          profile: minimal\n          toolchain: ${{ matrix.rust }}\n          override: true\n      - run: rustup component add clippy\n      - uses: actions-rs/cargo@v1\n        with:\n          command: clippy\n          args: -- -D warnings\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n\n## [Unreleased]\n\n### Added\n\n#### REPL\n\n- Basic help system\n- Ability to define custom variables and functions\n- Proper formatting for parse errors\n\n### Changed\n\n### Fixed\n\n\n## [0.2.0] - 2022-03-13\n\n### Added\n\n#### Core\n\n- Basic support for vectors and matrices\n- Algebraic simplification during evaluation\n- Infrastructure for evaluating functions\n- Macro-based function dispatch system\n- New built-in functions:\n  - `and`\n  - `det`\n  - `factorial`\n  - `is_prime`\n  - `nth_prime`\n  - `prime_pi`\n\n#### REPL\n\n- Persistent input history\n- Multi-line editing mode\n- Syntax highlighting for input and output\n- Highlighting of matching brackets in input\n\n### Fixed\n\n#### Core\n\n- Type inflation in parser\n- Exponential blowup in parser\n\n#### REPL\n\n- Error on empty input\n\n\n## [0.1.0] - 2021-11-28\n\nInitial release with basic REPL and support for elementary arithmetic and logic.\n\n\n[unreleased]: https://github.com/p-e-w/savage/compare/v0.2.0...HEAD\n[0.2.0]: https://github.com/p-e-w/savage/compare/v0.1.0...v0.2.0\n[0.1.0]: https://github.com/p-e-w/savage/releases/tag/v0.1.0\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[workspace]\nmembers = [\n    \"savage_macros\",\n    \"savage_core\",\n    \"savage\",\n]\n\n[profile.release]\ncodegen-units = 1\nopt-level = 3\nlto = true\n#strip = true\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "# Savage Computer Algebra System\n\nSavage is a new computer algebra system written from scratch in pure Rust.\nIts goals are correctness, simplicity, and usability, in that order.\nThe entire system compiles to a single, dependency-free executable just\n2.5 MB in size. While that executable will of course grow as Savage matures,\nthe plan is to eventually deliver a useful computer algebra system in 5 MB\nor less.\n\n![Screenshot](https://user-images.githubusercontent.com/2702526/158006796-7d3aad2a-217f-421a-b3f8-20498d32b0f0.png)\n\nThe name \"Savage\" is a reference/homage to [Sage](https://www.sagemath.org/),\nthe leading open-source computer algebra system. Since Sage already exists\nand works very well, it would make no sense to attempt to create a clone of it.\nInstead, Savage aims to be something of an antithesis to Sage: Where Sage is\na unified frontend to dozens of mathematics packages, Savage is a tightly-integrated,\nmonolithic system. Where Sage covers many areas of mathematics, including cutting-edge\nresearch topics, Savage will focus on the \"bread and butter\" math employed by\nengineers and other people who *use*, rather than develop, mathematical concepts.\nWhere Sage features amazingly sophisticated implementations of countless functions,\nSavage has code that is savagely primitive, getting the job done naively but correctly,\nwithout worrying whether the performance is still optimal when the input is\na million-digit number.\n\n**Savage is in early development and is not yet ready to be used for serious work.**\nIt is, however, ready to play around with, and is happily accepting contributions\nto move the project forward.\n\n\n## Features\n\nThis is what Savage offers **today:**\n\n* Arbitrary-precision integer, rational, and complex arithmetic\n* Input, simplification, and evaluation of symbolic expressions\n* First-class support for vectors and matrices, with coefficients being arbitrary expressions\n* REPL with syntax and bracket highlighting, persistent history, and automatic multi-line input\n* Macro-based system for defining functions with metadata and automatic type checking\n* [Usable as a library](#savage-as-a-library) from any Rust program\n\nThe following features are **planned,** with some of the groundwork already done:\n\n* User-defined variables and functions\n* Built-in help system\n* Many more functions from various areas of math\n* More powerful expression simplification\n* Jupyter kernel\n\nBy contrast, the following are considered **non-features** for Savage,\nand there are no plans to add them either now or in the future:\n\n* *Advanced/research-level mathematics:* As a rule of thumb, if it doesn't belong\n  in a typical undergraduate course, it probably doesn't belong in Savage.\n* *Physics/finance/machine learning/other areas adjacent to math:* The scope would\n  grow without bounds and that is exactly what Savage aims to avoid.\n* *Formal verification of implementations:* The required technologies aren't mature yet\n  and Savage is not a research project.\n* *Performance at the expense of simplicity:* Yes, I know that multiplication\n  can be done faster using some fancy Fourier tricks. No, I won't implement that.\n* *General-purpose programming:* Too complex, and not the focus of this project.\n* *File/network I/O:* Savage performs computations, nothing more and nothing less.\n  Functions have no side effects.\n* *Modules/packages/extensions/plugins:* The world is complicated enough.\n  Either something is built in, or Savage doesn't have it at all.\n* *GUI:* Although it's possible to create a GUI frontend backed by the `savage_core`\n  crate, there are no plans to do so within the Savage project itself.\n\n\n## Installation\n\nBuilding Savage from source requires [Rust](https://www.rust-lang.org/) **1.56 or later.**\nOnce a supported version of Rust is installed on your system, you only need to run\n\n```\ncargo install savage\n```\n\nto install the Savage REPL to your Cargo binary directory (usually `$HOME/.cargo/bin`).\nOf course, you can also just clone this repository and `cargo run` the REPL from the\nrepository root.\n\nIn the future, there will be pre-built executables for major platforms\navailable with every Savage release.\n\n\n## Tour\n\n### Arithmetic\n\nArithmetic operations in Savage have no precision limits (other than the amount\nof memory available in your system):\n\n```\nin: 1 + 1\nout: 2\n\nin: 1.1 ^ 100\nout: 13780.612339822270184118337172089636776264331200038466433146477552154985209\n5523076769401159497458526446001\n\nin: 3 ^ 4 ^ 5\nout: 373391848741020043532959754184866588225409776783734007750636931722079040617\n26525122999368893880397722046876506543147515810872705459216085858135133698280918\n73141917485942625809388070199519564042855718180410466812887974029255176680123406\n17298396574731619152386723046235125934896058590588284654793540505936202376547807\n44273058214452705898875625145281779341335214192074462302751872918543286237573706\n39854853194764169262638199728870069070138992565242971985276987492741962768110607\n02333710356481\n```\n\nResults are automatically printed in either fractional or decimal form,\ndepending on whether the input contained fractions or decimal numbers:\n\n```\nin: 6/5 * 3\nout: 18/5\n\nin: 1.2 * 3\nout: 3.6\n```\n\nThe variable `i` is predefined to represent the imaginary unit, allowing for\ncomplex numbers to be entered using standard notation:\n\n```\nin: (1 + i) ^ 12\nout: -64\n```\n\n### Linear algebra\n\nVectors and matrices are first-class citizens in Savage and support the standard\naddition, subtraction, multiplication, and exponentiation operators. Coefficients\ncan be arbitrary expressions:\n\n```\nin: [a, b] - [a, c]\nout: [0, b - c]\n\nin: [a, b, c] * 3\nout: [a * 3, b * 3, c * 3]\n\nin: [[1, 2], [3, 4]] * [5, 6]\nout: [17, 39]\n```\n\nDeterminants are evaluated symbolically:\n\n```\nin: det([[a, 2], [3, a]])\nout: a ^ 2 - 6\n```\n\n### Logic\n\nThe standard `&&`, `||`, `!`, and comparison operators are available. Savage\nautomatically evaluates many tautologies and contradictions, even in the presence\nof undefined variables:\n\n```\nin: a && true\nout: a\n\nin: a || true\nout: true\n\nin: a || !a\nout: true\n\nin: a < a\nout: false\n```\n\n### Number theory\n\nVerify that the Mersenne number *M<sub>31</sub>* is a prime number:\n\n```\nin: is_prime(2^31 - 1)\nout: true\n```\n\nCompute the ten millionth prime number:\n\n```\nin: nth_prime(10^7)\nout: 179424673\n```\n\nCompute the number of primes up to ten million:\n\n```\nin: prime_pi(10^7)\nout: 664579\n```\n\nThese functions for dealing with prime numbers are powered by the ultra-fast\n[`primal`](https://crates.io/crates/primal) crate. Many more functions from\nnumber theory will be added to Savage in the future.\n\n\n## Savage as a library\n\nAll of Savage's actual computer algebra functionality is contained in the\n[`savage_core`](https://crates.io/crates/savage_core) crate. That crate exposes\neverything necessary to build software that leverages symbolic math capabilities.\nAssuming `savage_core` has been added as a dependency to a crate's `Cargo.toml`,\nit can be used like this:\n\n```rust\nuse std::collections::HashMap;\n\nuse savage_core::{expression::Expression, helpers::*};\n\nfn main() {\n    // Expressions can be constructed by parsing a string literal...\n    let lhs = \"det([[a, 2], [3, a]])\".parse::<Expression>().unwrap();\n    // ... or directly from code using helper functions.\n    let rhs = pow(var(\"a\"), int(2)) - int(6);\n\n    let mut context = HashMap::new();\n    // The context can be used to set the values of variables during evaluation.\n    // Change \"b\" to \"a\" to see this in action!\n    context.insert(\"b\".to_owned(), int(3));\n\n    assert_eq!(lhs.evaluate(context), Ok(rhs));\n}\n```\n\nPlease note that at this point, the primary purpose of the `savage_core` crate is\nto power the Savage REPL, so any use by third-party crates should be considered\nsomewhat experimental. Note also that like the rest of Savage, `savage_core` is\nlicensed under the terms of the [AGPL](LICENSE), which imposes conditions on any\ndependent software that go beyond what is required by the more common permissive\nlicenses. Make sure you understand the AGPL and its implications before adding\n`savage_core` as a dependency to your crate.\n\n\n## Acknowledgments\n\nSavage stands on the shoulders of the giant that is the Rust ecosystem. Among the\nmany third-party crates that Savage relies on, I want to highlight two that play\na particularly important role:\n\n* [`num`](https://crates.io/crates/num) is the fundamental crate for all numeric\n  computations in Savage. It provides the crucial `BigInt` type that enables\n  standard arithmetic operations to be performed with arbitrary precision.\n  `num`'s code is of high quality and extremely well tested.\n* [`chumsky`](https://crates.io/crates/chumsky) is the magic behind Savage's expression\n  parser. I have looked at every parser crate currently available and found Chumsky's\n  API to be by far the most intuitive. Furthermore, Chumsky's author is highly\n  responsive on the issue tracker, and has personally helped me understand and resolve\n  two major issues that arose during the development of Savage's parser.\n\n\n## License\n\nCopyright &copy; 2021-2022  Philipp Emanuel Weidmann (<pew@worldwidemann.com>)\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\n**By contributing to this project, you agree to release your\ncontributions under the same license.**\n"
  },
  {
    "path": "savage/Cargo.toml",
    "content": "[package]\nname = \"savage\"\nversion = \"0.2.0\"\nauthors = [\"Philipp Emanuel Weidmann <pew@worldwidemann.com>\"]\ndescription = \"A primitive computer algebra system (REPL)\"\nrepository = \"https://github.com/p-e-w/savage\"\nreadme = \"README.md\"\nlicense = \"AGPL-3.0-or-later\"\nedition = \"2021\"\n\n[dependencies]\nlazy_static = \"1.4.0\"\ndirectories = \"4.0.1\"\ncrossterm = \"0.25.0\"\nansi_term = \"0.12.1\"\nrustyline = \"9.0.0\"\nrustyline-derive = \"0.7.0\"\ntermimad = \"0.20.2\"\nregex = \"1.6.0\"\nchumsky = \"0.8.0\"\nariadne = \"0.1.5\"\nsavage_core = { path = \"../savage_core\", version = \"0.2.0\" }\n"
  },
  {
    "path": "savage/help/footer.md",
    "content": "## License\n\nCopyright (C) 2021-2022  Philipp Emanuel Weidmann (**pew@worldwidemann.com**)\n\nThis 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.\n\nThis 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.\n\nYou should have received a copy of the GNU Affero General Public License along with this program. If not, see **https://www.gnu.org/licenses/**.\n"
  },
  {
    "path": "savage/help/header.md",
    "content": "# Savage Computer Algebra System\n\nSavage is a new computer algebra system written from scratch in pure Rust. Its goals are correctness, simplicity, and usability, in that order.\n\nThis is Savage's documentation, which may be viewed at any time by entering `?` in the REPL (**r**ead-**e**val-**p**rint **l**oop, i.e. the Savage command interpreter). You can also directly view the documentation for a specific built-in function by entering `?` followed by the name of the function, e.g. `? det` for the determinant function.\n\nFor more information, visit **https://github.com/p-e-w/savage**. Note that Savage is in early development. If you encounter bugs or other problems, please don't hesitate to file an issue.\n\n\n## Basic usage\n\nType mathematical expressions in the REPL using standard notation and press *Enter* to evaluate them:\n\n```\nin: 1 + 1\nout: 2\n```\n\nSavage supports integer (`123`), fractional (`1/2`), decimal (`1.23`), and complex (`1 + 2*i`) number literals, as well as the sum (`+`), difference (`-`), product (`*`), quotient (`/`), remainder (`%`), and power (`^`) binary operators, and the negation (`-`) prefix operator:\n\n```\nin: 6/5 * 3\nout: 18/5\n\nin: 1.2 * 3\nout: 3.6\n\nin: (1 + i) ^ 12\nout: -64\n```\n\nIt also supports boolean (`true`/`false`) literals, and the conjunction (\"and\", `&&`), disjunction (\"or\", `||`), and logical negation (\"not\", `!`) operators. The standard comparison operators (`==`, `!=`, `<`, `<=`, `>`, `>=`) are available as well:\n\n```\nin: a && true\nout: a\n\nin: a || true\nout: true\n\nin: a || !a\nout: true\n\nin: a < a\nout: false\n```\n\n\n## Vectors and matrices\n\nA comma-separated list of expressions surrounded by square brackets (e.g. `[1, 2, 3]`) represents a column vector with the expressions as elements. A vector of vectors, all of which have the same size (e.g. `[[1, 2], [3, 4]]`), is interpreted as a column-major matrix whose rows are the constitutent vectors.\n\nVectors and matrices support the standard arithmetic operations:\n\n```\nin: [a, b] - [a, c]\nout: [0, b - c]\n\nin: [a, b, c] * 3\nout: [a * 3, b * 3, c * 3]\n\nin: [[1, 2], [3, 4]] * [5, 6]\nout: [17, 39]\n```\n\nIndividual elements of vectors and matrices can be accessed using the index notation familiar from many programming languages:\n\n```\nin: v = [1, 2, 3]\nin: v[1]\nout: 2\n\nin: m = [[1, 2], [3, 4]]\nin: m[1, 0]\nout: 3\n```\n\n\n## Variables and functions\n\nSymbolic names like `a`, `b`, and `c` are by default interpreted as expression placeholders. They can, however, be assigned specific values, at which point they become defined variables:\n\n```\nin: a = 1\nin: b = 2\nin: a + b\nout: 3\n```\n\nFunctions can also be defined with a syntax that is essentially identical to that used in standard mathematical notation:\n\n```\nin: sum(x, y) = x + y\nin: sum(1, 2)\nout: 3\n```\n\n\n## Built-in functions\n\nThe following named functions are available in the REPL without needing to be explicitly loaded or manually defined:\n"
  },
  {
    "path": "savage/src/command.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse std::str::FromStr;\n\nuse chumsky::prelude::*;\nuse savage_core::{\n    expression::Expression,\n    parse::{parser as expression, Error},\n};\n\n#[derive(PartialEq, Eq, Clone, Debug)]\npub enum Command {\n    EvaluateExpression(Expression),\n    DefineVariable(String, Expression),\n    DefineFunction(String, Vec<String>, Expression),\n    ShowHelp(Option<String>),\n}\n\nfn parser() -> impl Parser<char, Command, Error = Error> {\n    text::ident()\n        .padded()\n        .then_ignore(just('='))\n        .then(expression())\n        .map(|(identifier, expression)| Command::DefineVariable(identifier, expression))\n        .or(text::ident()\n            .padded()\n            .then(\n                text::ident()\n                    .padded()\n                    .separated_by(just(','))\n                    .padded()\n                    .delimited_by(just('('), just(')'))\n                    .padded(),\n            )\n            .then_ignore(just('='))\n            .then(expression())\n            .map(|((identifier, argument_identifiers), expression)| {\n                Command::DefineFunction(identifier, argument_identifiers, expression)\n            }))\n        .or(expression().map(Command::EvaluateExpression))\n        .or(just('?')\n            .padded()\n            .ignore_then(text::ident().padded().or_not())\n            .map(Command::ShowHelp))\n}\n\nimpl FromStr for Command {\n    type Err = Vec<Error>;\n\n    fn from_str(string: &str) -> Result<Self, Self::Err> {\n        parser().then_ignore(end()).parse(string)\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use savage_core::helpers::*;\n\n    use crate::command::{Command, Command::*};\n\n    #[track_caller]\n    fn t(string: &str, command: Command) {\n        assert_eq!(string.parse(), Ok(command));\n    }\n\n    #[test]\n    fn parse() {\n        t(\"   a \", EvaluateExpression(var(\"a\")));\n        t(\"a ==b \", EvaluateExpression(eq(var(\"a\"), var(\"b\"))));\n\n        t(\" a=1\", DefineVariable(\"a\".to_owned(), int(1)));\n        t(\n            \"a   =b==  c\",\n            DefineVariable(\"a\".to_owned(), eq(var(\"b\"), var(\"c\"))),\n        );\n\n        t(\"f(  )= 1\", DefineFunction(\"f\".to_owned(), vec![], int(1)));\n        t(\n            \" f (x) =x ^ 2\",\n            DefineFunction(\"f\".to_owned(), vec![\"x\".to_owned()], pow(var(\"x\"), int(2))),\n        );\n        t(\n            \"f( x )=( (x)== (y))  \",\n            DefineFunction(\"f\".to_owned(), vec![\"x\".to_owned()], eq(var(\"x\"), var(\"y\"))),\n        );\n        t(\n            \"f( x ,y)= g(x, y)\",\n            DefineFunction(\n                \"f\".to_owned(),\n                vec![\"x\".to_owned(), \"y\".to_owned()],\n                fun(var(\"g\"), [var(\"x\"), var(\"y\")]),\n            ),\n        );\n\n        t(\" ?  \", ShowHelp(None));\n        t(\"?is_prime  \", ShowHelp(Some(\"is_prime\".to_owned())));\n        t(\"?  is_prime\", ShowHelp(Some(\"is_prime\".to_owned())));\n    }\n}\n"
  },
  {
    "path": "savage/src/help.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse std::{\n    collections::HashMap,\n    io::{stdout, Write},\n};\n\nuse crossterm::{\n    cursor,\n    event::{self, Event, KeyEvent},\n    queue,\n    style::Stylize,\n    terminal::{\n        self, ClearType, DisableLineWrap, EnableLineWrap, EnterAlternateScreen,\n        LeaveAlternateScreen,\n    },\n};\nuse lazy_static::lazy_static;\nuse savage_core::functions::functions;\nuse termimad::{Area, Error, MadSkin, MadView};\n\nconst HELP_HEADER: &str = include_str!(\"../help/header.md\");\nconst HELP_FOOTER: &str = include_str!(\"../help/footer.md\");\n\nlazy_static! {\n    pub static ref FUNCTION_HELP_TEXTS: HashMap<String, String> = {\n        let mut texts = HashMap::new();\n\n        for function in functions() {\n            let metadata = function.metadata;\n\n            let text = format!(\n                \"**{}** - {}\\n\\n*Syntax:*\\n```\\n{}({})\\n```\\n\\n*Examples:*\\n```\\n{}\\n```\\n\\n*Categories:*\\n{}\\n\",\n                metadata.name,\n                metadata.description,\n                metadata.name,\n                metadata\n                    .parameters\n                    .iter()\n                    .map(|p| format!(\"{:?}\", p))\n                    .collect::<Vec<_>>()\n                    .join(\", \"),\n                metadata\n                    .examples\n                    .iter()\n                    .map(|(i, o)| format!(\"in: {}\\nout: {}\", i, o))\n                    .collect::<Vec<_>>()\n                    .join(\"\\n\\n\"),\n                metadata.categories.join(\", \"),\n            );\n\n            texts.insert(metadata.name.to_owned(), text);\n        }\n\n        texts\n    };\n    pub static ref HELP_TEXT: String = {\n        let mut text = String::from(HELP_HEADER);\n\n        text.push_str(\"\\n---\\n\\n\");\n\n        for function in functions() {\n            text.push_str(&FUNCTION_HELP_TEXTS[function.metadata.name]);\n            text.push_str(\"\\n---\\n\\n\");\n        }\n\n        text.push('\\n');\n        text.push_str(HELP_FOOTER);\n        text.push('\\n');\n\n        text\n    };\n}\n\nfn view_area() -> Area {\n    let mut area = Area::full_screen();\n\n    area.pad_for_max_width(120);\n\n    // Make space for bottom bar.\n    area.height -= 1;\n\n    area\n}\n\npub fn show_help(text: String) -> Result<(), Error> {\n    // Based on https://github.com/Canop/termimad/blob/5ab13e600f05c0217e270181dd5d9288210f893f/examples/scrollable/main.rs\n    use crossterm::event::KeyCode::*;\n\n    let mut stdout = stdout();\n\n    queue!(stdout, EnterAlternateScreen, DisableLineWrap, cursor::Hide)?;\n    terminal::enable_raw_mode()?;\n\n    let mut view = MadView::from(text, view_area(), MadSkin::default());\n\n    loop {\n        view.write_on(&mut stdout)?;\n\n        print!(\n            \"\\n\\r{}{}{}{}{}{}{}{}\",\n            \"Press \".reverse(),\n            \"\\u{2191}\".bold().reverse(),\n            \" and \".reverse(),\n            \"\\u{2193}\".bold().reverse(),\n            \" to scroll, \".reverse(),\n            \"Q\".bold().reverse(),\n            \" to quit\".reverse(),\n            \" \".repeat(view_area().width as usize).reverse(),\n        );\n\n        stdout.flush()?;\n\n        match event::read() {\n            Ok(Event::Key(KeyEvent { code, .. })) => match code {\n                Up | Char('k') => view.try_scroll_lines(-1),\n                Down | Char('j') | Enter => view.try_scroll_lines(1),\n                PageUp => view.try_scroll_pages(-1),\n                PageDown | Char(' ') => view.try_scroll_pages(1),\n                Char('q') | Esc => break,\n                _ => {}\n            },\n            Ok(Event::Resize(..)) => {\n                queue!(stdout, terminal::Clear(ClearType::All))?;\n                view.resize(&view_area());\n            }\n            _ => {}\n        }\n    }\n\n    terminal::disable_raw_mode()?;\n    queue!(stdout, cursor::Show, EnableLineWrap, LeaveAlternateScreen)?;\n    stdout.flush()?;\n\n    Ok(())\n}\n"
  },
  {
    "path": "savage/src/input.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse std::borrow::Cow;\n\nuse ansi_term::Style;\nuse lazy_static::lazy_static;\nuse regex::Regex;\nuse rustyline::{\n    highlight::Highlighter,\n    validate::{ValidationContext, ValidationResult, Validator},\n    Result,\n};\nuse rustyline_derive::{Completer, Helper, Hinter};\nuse savage_core::{expression::Expression, parse::ErrorReason};\n\nenum TokenType {\n    Literal,\n    Variable,\n    Operator,\n    Bracket,\n    Separator,\n    Whitespace,\n    Invalid,\n}\n\nfn tokenize(input: &str) -> Vec<(String, TokenType)> {\n    use TokenType::*;\n\n    lazy_static! {\n        static ref REGEX: Regex = Regex::new(\n            &[\n                r\"(?P<literal>[0-9]+(?:\\.[0-9]+)?|true|false)\",\n                r\"(?P<variable>[a-zA-Z_][a-zA-Z0-9_]*)\",\n                r\"(?P<operator>[+\\-*/%^!=<>&|]+)\",\n                r\"(?P<bracket>[()\\[\\]])\",\n                r\"(?P<separator>,)\",\n                r\"(?P<whitespace>\\s+)\",\n            ]\n            .join(\"|\"),\n        )\n        .unwrap();\n    }\n\n    let mut tokens = Vec::new();\n\n    let mut last_token_end = 0;\n\n    for captures in REGEX.captures_iter(input) {\n        let token_type = if captures.name(\"literal\").is_some() {\n            Literal\n        } else if captures.name(\"variable\").is_some() {\n            Variable\n        } else if captures.name(\"operator\").is_some() {\n            Operator\n        } else if captures.name(\"bracket\").is_some() {\n            Bracket\n        } else if captures.name(\"separator\").is_some() {\n            Separator\n        } else if captures.name(\"whitespace\").is_some() {\n            Whitespace\n        } else {\n            unreachable!()\n        };\n\n        let token_range = captures.get(0).unwrap().range();\n\n        if last_token_end < token_range.start {\n            tokens.push((input[last_token_end..token_range.start].to_owned(), Invalid));\n        }\n\n        last_token_end = token_range.end;\n\n        tokens.push((input[token_range].to_owned(), token_type));\n    }\n\n    if last_token_end < input.len() {\n        tokens.push((input[last_token_end..].to_owned(), Invalid));\n    }\n\n    tokens\n}\n\n#[derive(Completer, Helper, Hinter)]\npub struct InputHelper {}\n\nimpl Highlighter for InputHelper {\n    fn highlight_prompt<'b, 's: 'b, 'p: 'b>(\n        &'s self,\n        prompt: &'p str,\n        _default: bool,\n    ) -> Cow<'b, str> {\n        Cow::Owned(Style::new().bold().paint(prompt).to_string())\n    }\n\n    fn highlight<'l>(&self, line: &'l str, pos: usize) -> Cow<'l, str> {\n        use ansi_term::Colour::*;\n        use TokenType::*;\n\n        let matching_pos = if pos < line.len() {\n            let line_bytes = line.as_bytes();\n\n            let mut matching_pos = None;\n\n            'outer: for (open, close) in [(b'(', b')'), (b'[', b']')] {\n                let (range, open, close): (Box<dyn Iterator<Item = usize>>, _, _) =\n                    if line_bytes[pos] == open {\n                        (Box::new(pos + 1..line_bytes.len()), open, close)\n                    } else if line_bytes[pos] == close {\n                        (Box::new((0..pos).rev()), close, open)\n                    } else {\n                        continue;\n                    };\n\n                let mut closes_needed = 1;\n\n                for i in range {\n                    if line_bytes[i] == open {\n                        closes_needed += 1;\n                    } else if line_bytes[i] == close {\n                        closes_needed -= 1;\n\n                        if closes_needed == 0 {\n                            matching_pos = Some(i);\n                            break 'outer;\n                        }\n                    }\n                }\n            }\n\n            matching_pos\n        } else {\n            None\n        };\n\n        let mut highlighted_line = String::new();\n\n        let mut token_pos = 0;\n\n        for (token, token_type) in tokenize(line) {\n            let mut style = match token_type {\n                Literal => Cyan.into(),\n                Variable => Green.into(),\n                Operator => Purple.into(),\n                Bracket => Style::new(),\n                Separator => Style::new(),\n                Whitespace => Style::new(),\n                Invalid => Red.into(),\n            };\n\n            if Some(token_pos) == matching_pos {\n                style = style.bold();\n            }\n\n            token_pos += token.len();\n\n            // https://github.com/rust-lang/rust-clippy/issues/9317\n            #[allow(clippy::unnecessary_to_owned)]\n            highlighted_line.push_str(&style.paint(token).to_string());\n        }\n\n        Cow::Owned(highlighted_line)\n    }\n\n    fn highlight_char(&self, _line: &str, _pos: usize) -> bool {\n        true\n    }\n}\n\nimpl Validator for InputHelper {\n    fn validate(&self, ctx: &mut ValidationContext) -> Result<ValidationResult> {\n        // This implementation distinguishes only between \"incomplete\"\n        // (unexpected end of input) and \"valid\" (everything else),\n        // because actual input validation is performed by the REPL\n        // as part of the regular input processing step.\n        let input = ctx.input();\n\n        if input.trim().is_empty() || input.ends_with('\\n') {\n            return Ok(ValidationResult::Valid(None));\n        }\n\n        if let Err(errors) = input.parse::<Expression>() {\n            for error in errors {\n                if error.reason() == &ErrorReason::Unexpected && error.found() == None {\n                    return Ok(ValidationResult::Incomplete);\n                }\n            }\n        }\n\n        Ok(ValidationResult::Valid(None))\n    }\n}\n"
  },
  {
    "path": "savage/src/main.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nmod command;\nmod help;\nmod input;\n\nuse std::{\n    collections::{HashMap, HashSet},\n    fs,\n    iter::FromIterator,\n    rc::Rc,\n};\n\nuse ansi_term::Style;\nuse ariadne::{Color, Fmt, Label, Report, ReportKind, Source};\nuse directories::ProjectDirs;\nuse lazy_static::lazy_static;\nuse rustyline::{error::ReadlineError, highlight::Highlighter, Editor};\nuse savage_core::{\n    evaluate::{default_context, Error as EvaluateError},\n    expression::{Expression, Vector},\n    parse::{Error as ParseError, ErrorReason},\n};\n\nuse crate::{\n    command::Command,\n    help::{show_help, FUNCTION_HELP_TEXTS, HELP_TEXT},\n    input::InputHelper,\n};\n\nlazy_static! {\n    static ref RESERVED_IDENTIFIERS: HashSet<String> =\n        HashSet::from([\"true\", \"false\", \"out\"].map(str::to_owned));\n}\n\nfn format_parse_error(error: ParseError) -> Report {\n    // Heavily based on https://github.com/zesterer/chumsky/blob/463226372cf293d45bd5df52bf25d5028243066e/examples/json.rs#L114-L173\n    let message = if let ErrorReason::Custom(message) = error.reason() {\n        message.clone()\n    } else {\n        format!(\n            \"{}, expected {}\",\n            if error.found().is_some() {\n                \"Unexpected token\"\n            } else {\n                \"Unexpected end of input\"\n            },\n            if error.expected().len() == 0 {\n                \"something else\".to_string()\n            } else {\n                error\n                    .expected()\n                    .map(|expected| match expected {\n                        Some(expected) => expected.to_string(),\n                        None => \"end of input\".to_string(),\n                    })\n                    .collect::<Vec<_>>()\n                    .join(\", \")\n            },\n        )\n    };\n\n    let report = Report::build(ReportKind::Error, (), error.span().start)\n        .with_message(message)\n        .with_label(\n            Label::new(error.span())\n                .with_message(match error.reason() {\n                    ErrorReason::Custom(message) => message.clone(),\n                    _ => format!(\n                        \"Unexpected {}\",\n                        error\n                            .found()\n                            .map(|c| format!(\"token {}\", c.fg(Color::Red)))\n                            .unwrap_or_else(|| \"end of input\".to_string()),\n                    ),\n                })\n                .with_color(Color::Red),\n        );\n\n    let report = match error.reason() {\n        ErrorReason::Unclosed { span, delimiter } => report.with_label(\n            Label::new(span.clone())\n                .with_message(format!(\n                    \"Unclosed delimiter {}\",\n                    delimiter.fg(Color::Yellow),\n                ))\n                .with_color(Color::Yellow),\n        ),\n        ErrorReason::Unexpected => report,\n        ErrorReason::Custom(_) => report,\n    };\n\n    report.finish()\n}\n\nfn main() {\n    use crate::command::Command::*;\n\n    let history_path = ProjectDirs::from(\"com.worldwidemann\", \"\", \"Savage\")\n        .expect(\"unable to locate data directory\")\n        .data_dir()\n        .join(\"history\");\n\n    let mut editor = Editor::new();\n\n    editor.set_helper(Some(InputHelper {}));\n\n    editor.load_history(&history_path).ok();\n\n    println!(\n        \"Savage Computer Algebra System {}\",\n        env!(\"CARGO_PKG_VERSION\"),\n    );\n\n    println!(\n        \"Enter {} for help, press {} to quit, {} to cancel evaluation\",\n        Style::new().bold().paint(\"?\"),\n        Style::new().bold().paint(\"Ctrl+D\"),\n        Style::new().bold().paint(\"Ctrl+C\"),\n    );\n\n    let mut outputs = Vec::new();\n\n    let mut context = default_context();\n\n    context.insert(\n        \"out\".to_owned(),\n        Expression::Vector(Vector::from_vec(outputs.clone())),\n    );\n\n    'outer: loop {\n        println!();\n\n        match editor.readline(\"in: \") {\n            Ok(line) => {\n                let line = line.trim();\n\n                if line.is_empty() {\n                    continue;\n                }\n\n                editor.add_history_entry(line);\n\n                match line.parse::<Command>() {\n                    Ok(EvaluateExpression(expression)) => match expression.evaluate(&context) {\n                        Ok(output) => {\n                            println!(\n                                \"{}{}\",\n                                Style::new()\n                                    .bold()\n                                    .paint(format!(\"out[{}]: \", outputs.len())),\n                                editor\n                                    .helper()\n                                    .unwrap()\n                                    .highlight(&output.to_string(), usize::MAX),\n                            );\n\n                            outputs.push(output);\n\n                            context.insert(\n                                \"out\".to_owned(),\n                                Expression::Vector(Vector::from_vec(outputs.clone())),\n                            );\n                        }\n                        Err(error) => println!(\"Error: {:#?}\", error),\n                    },\n                    Ok(DefineVariable(identifier, expression)) => {\n                        if RESERVED_IDENTIFIERS.contains(&identifier) {\n                            println!(\"Error: \\\"{}\\\" is a reserved identifier and cannot be used as a variable name.\", identifier);\n                            continue;\n                        }\n\n                        match expression.evaluate(&context) {\n                            Ok(expression) => {\n                                let variables = expression.variables();\n\n                                if !variables.is_empty() {\n                                    println!(\"Error: The assigned expression contains the undefined variable(s) {}.\", Vec::from_iter(variables).join(\", \"));\n                                    continue;\n                                }\n\n                                context.insert(identifier, expression);\n                            }\n                            Err(error) => println!(\"Error: {:#?}\", error),\n                        }\n                    }\n                    Ok(DefineFunction(identifier, argument_identifiers, expression)) => {\n                        if RESERVED_IDENTIFIERS.contains(&identifier) {\n                            println!(\"Error: \\\"{}\\\" is a reserved identifier and cannot be used as a function name.\", identifier);\n                            continue;\n                        }\n\n                        let mut inner_context = context.clone();\n\n                        for argument_identifier in &argument_identifiers {\n                            if RESERVED_IDENTIFIERS.contains(argument_identifier) {\n                                println!(\"Error: \\\"{}\\\" is a reserved identifier and cannot be used as an argument name.\", argument_identifier);\n                                continue 'outer;\n                            }\n\n                            if argument_identifiers\n                                .iter()\n                                .filter(|&id| id == argument_identifier)\n                                .count()\n                                > 1\n                            {\n                                println!(\n                                    \"Error: The name \\\"{}\\\" is used for more than one argument.\",\n                                    argument_identifier,\n                                );\n                                continue 'outer;\n                            }\n\n                            inner_context.remove(argument_identifier);\n                        }\n\n                        match expression.evaluate(&inner_context) {\n                            Ok(expression) => {\n                                let mut variables = expression.variables();\n\n                                for argument_identifier in &argument_identifiers {\n                                    variables.remove(argument_identifier);\n                                }\n\n                                if !variables.is_empty() {\n                                    println!(\"Error: The assigned expression contains the undefined variable(s) {}.\", Vec::from_iter(variables).join(\", \"));\n                                    continue;\n                                }\n\n                                context.insert(\n                                    identifier.clone(),\n                                    Expression::Function(\n                                        identifier,\n                                        Rc::new(move |self_expression, arguments, _| {\n                                            if arguments.len() != argument_identifiers.len() {\n                                                return Err(\n                                                    EvaluateError::InvalidNumberOfArguments {\n                                                        expression: self_expression.clone(),\n                                                        min_number: argument_identifiers.len(),\n                                                        max_number: argument_identifiers.len(),\n                                                        given_number: arguments.len(),\n                                                    },\n                                                );\n                                            }\n\n                                            // Both the default context and the outer context the function is being\n                                            // evaluated in can be ignored, since it was already checked that the\n                                            // expression contains no variables other than the argument identifiers.\n                                            let mut context = HashMap::new();\n\n                                            for (identifier, argument) in\n                                                argument_identifiers.iter().zip(arguments)\n                                            {\n                                                context\n                                                    .insert(identifier.clone(), argument.clone());\n                                            }\n\n                                            expression.evaluate(&context)\n                                        }),\n                                    ),\n                                );\n                            }\n                            Err(error) => println!(\"Error: {:#?}\", error),\n                        }\n                    }\n                    Ok(ShowHelp(function_name)) => {\n                        if let Some(function_name) = function_name {\n                            if let Some(function_help_text) =\n                                FUNCTION_HELP_TEXTS.get(&function_name)\n                            {\n                                show_help(function_help_text.clone()).expect(\"unable to show help\");\n                            } else {\n                                println!(\n                                    \"Error: No help text available for the function {}.\",\n                                    function_name,\n                                );\n                            }\n                        } else {\n                            show_help(HELP_TEXT.clone()).expect(\"unable to show help\");\n                        }\n                    }\n                    Err(errors) => {\n                        for error in errors {\n                            format_parse_error(error)\n                                .print(Source::from(line))\n                                .expect(\"unable to print parse error\");\n                        }\n                    }\n                }\n            }\n            Err(ReadlineError::Interrupted | ReadlineError::Eof) => {\n                break;\n            }\n            Err(error) => {\n                println!(\"Error: {:#?}\", error);\n                break;\n            }\n        }\n    }\n\n    fs::create_dir_all(\n        history_path\n            .parent()\n            .expect(\"unable to determine parent directory of history file\"),\n    )\n    .expect(\"unable to create data directory\");\n\n    editor\n        .save_history(&history_path)\n        .expect(\"unable to save input history\");\n}\n"
  },
  {
    "path": "savage_core/Cargo.toml",
    "content": "[package]\nname = \"savage_core\"\nversion = \"0.2.0\"\nauthors = [\"Philipp Emanuel Weidmann <pew@worldwidemann.com>\"]\ndescription = \"A primitive computer algebra system (library)\"\nrepository = \"https://github.com/p-e-w/savage\"\nreadme = \"README.md\"\nlicense = \"AGPL-3.0-or-later\"\nedition = \"2021\"\n\n[dependencies]\nnum = \"0.4.0\"\nnalgebra = \"0.31.1\"\npermutohedron = \"0.2.4\"\nprimal = \"0.3.0\"\nchumsky = \"0.8.0\"\nderivative = \"2.2.0\"\nsavage_macros = { path = \"../savage_macros\", version = \"0.1.0\" }\n"
  },
  {
    "path": "savage_core/src/evaluate.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse std::collections::HashMap;\n\nuse num::{One, ToPrimitive, Zero};\n\nuse crate::{\n    expression::{Complex, Expression, RationalRepresentation},\n    functions::functions,\n};\n\n/// Error that occurred while trying to evaluate an expression.\n#[derive(PartialEq, Eq, Clone, Debug)]\npub enum Error {\n    /// Operation on an expression that the operation is not defined for.\n    InvalidOperand {\n        expression: Expression,\n        operand: Expression,\n    },\n    /// Operation on two expressions that cannot be combined using the operation.\n    IncompatibleOperands {\n        expression: Expression,\n        operand_1: Expression,\n        operand_2: Expression,\n    },\n    /// Division by an expression that evaluates to zero (undefined).\n    DivisionByZero {\n        expression: Expression,\n        dividend: Expression,\n        divisor: Expression,\n    },\n    /// An expression that evaluates to zero raised to the power of\n    /// another expression that evaluates to zero (undefined).\n    ZeroToThePowerOfZero {\n        expression: Expression,\n        base: Expression,\n        exponent: Expression,\n    },\n    /// Vector or matrix expression indexed by an expression that evaluates to\n    /// an integer outside the range of valid indices for that vector or matrix.\n    IndexOutOfBounds {\n        expression: Expression,\n        vector_or_matrix: Expression,\n        index: Expression,\n    },\n    /// Function expression evaluated with a number of arguments\n    /// that is invalid for the function.\n    InvalidNumberOfArguments {\n        expression: Expression,\n        min_number: usize,\n        max_number: usize,\n        given_number: usize,\n    },\n    /// Function expression evaluated with an argument\n    /// that is invalid for the function in that position.\n    InvalidArgument {\n        expression: Expression,\n        argument: Expression,\n    },\n}\n\n/// Returns an evaluation context populated with standard variable and function definitions.\npub fn default_context() -> HashMap<String, Expression> {\n    let mut default_context = HashMap::new();\n\n    default_context.insert(\n        \"i\".to_owned(),\n        Expression::Complex(Complex::i(), RationalRepresentation::Fraction),\n    );\n\n    for function in functions() {\n        default_context.insert(\n            function.metadata.name.to_owned(),\n            Expression::Function(function.metadata.name.to_owned(), function.implementation),\n        );\n    }\n\n    default_context\n}\n\nimpl Expression {\n    /// Returns the result of performing a single evaluation step on\n    /// the unary operator expression `self` with operand `a`, or an error\n    /// if the expression cannot be evaluated. The `context` argument can be\n    /// used to set the values of variables by their identifiers.\n    fn evaluate_step_unary(\n        &self,\n        a: &Self,\n        context: &HashMap<String, Self>,\n    ) -> Result<Self, Error> {\n        use crate::expression::Expression::*;\n        use crate::expression::Type::{Arithmetic, Boolean as Bool, Matrix as Mat, Number as Num};\n        use Error::*;\n\n        let a_original = a;\n\n        let a = a.evaluate_step(context)?;\n\n        match (self, a.typ()) {\n            (Negation(_), Bool(_)) | (Not(_), Num(_, _) | Mat(_) | Arithmetic) => {\n                Err(InvalidOperand {\n                    expression: self.clone(),\n                    operand: a_original.clone(),\n                })\n            }\n\n            (Negation(_), Num(a, representation)) => Ok(Complex(-a, representation)),\n            (Negation(_), Mat(a)) => Ok(Matrix(-a)),\n            (Negation(_), _) => Ok(Negation(Box::new(a))),\n\n            (Not(_), Bool(Some(a))) => Ok(Boolean(!a)),\n            (Not(_), _) => Ok(Not(Box::new(a))),\n\n            (\n                Variable(_)\n                | Function(_, _)\n                | FunctionValue(_, _)\n                | Integer(_)\n                | Rational(_, _)\n                | Complex(_, _)\n                | Vector(_)\n                | VectorElement(_, _)\n                | Matrix(_)\n                | MatrixElement(_, _, _)\n                | Boolean(_)\n                | Sum(_, _)\n                | Difference(_, _)\n                | Product(_, _)\n                | Quotient(_, _)\n                | Remainder(_, _)\n                | Power(_, _)\n                | Equal(_, _)\n                | NotEqual(_, _)\n                | LessThan(_, _)\n                | LessThanOrEqual(_, _)\n                | GreaterThan(_, _)\n                | GreaterThanOrEqual(_, _)\n                | And(_, _)\n                | Or(_, _),\n                _,\n            ) => unreachable!(),\n        }\n    }\n\n    /// Returns the result of performing a single evaluation step on\n    /// the binary operator expression `self` with operands `a` and `b`,\n    /// or an error if the expression cannot be evaluated. The `context`\n    /// argument can be used to set the values of variables by their\n    /// identifiers.\n    fn evaluate_step_binary(\n        &self,\n        a: &Self,\n        b: &Self,\n        context: &HashMap<String, Self>,\n    ) -> Result<Self, Error> {\n        use crate::expression::Expression::*;\n        use crate::expression::Type::{Arithmetic, Boolean as Bool, Matrix as Mat, Number as Num};\n        use Error::*;\n\n        let a_original = a;\n        let b_original = b;\n\n        let a = a.evaluate_step(context)?;\n        let b = b.evaluate_step(context)?;\n\n        let a_evaluated = &a;\n        let b_evaluated = &b;\n\n        match (self, a.typ(), b.typ()) {\n            (\n                Sum(_, _)\n                | Difference(_, _)\n                | Product(_, _)\n                | Quotient(_, _)\n                | Remainder(_, _)\n                | Power(_, _),\n                Bool(_),\n                _,\n            )\n            | (\n                LessThan(_, _)\n                | LessThanOrEqual(_, _)\n                | GreaterThan(_, _)\n                | GreaterThanOrEqual(_, _),\n                Mat(_) | Bool(_),\n                _,\n            )\n            | (And(_, _) | Or(_, _), Num(_, _) | Mat(_) | Arithmetic, _) => Err(InvalidOperand {\n                expression: self.clone(),\n                operand: a_original.clone(),\n            }),\n\n            (\n                Sum(_, _)\n                | Difference(_, _)\n                | Product(_, _)\n                | Quotient(_, _)\n                | Remainder(_, _)\n                | Power(_, _),\n                _,\n                Bool(_),\n            )\n            | (\n                LessThan(_, _)\n                | LessThanOrEqual(_, _)\n                | GreaterThan(_, _)\n                | GreaterThanOrEqual(_, _),\n                _,\n                Mat(_) | Bool(_),\n            )\n            | (And(_, _) | Or(_, _), _, Num(_, _) | Mat(_) | Arithmetic) => Err(InvalidOperand {\n                expression: self.clone(),\n                operand: b_original.clone(),\n            }),\n\n            (Sum(_, _) | Difference(_, _) | Equal(_, _) | NotEqual(_, _), Num(_, _), Mat(_))\n            | (Sum(_, _) | Difference(_, _) | Equal(_, _) | NotEqual(_, _), Mat(_), Num(_, _))\n            | (Equal(_, _) | NotEqual(_, _), Num(_, _) | Mat(_), Bool(_))\n            | (Equal(_, _) | NotEqual(_, _), Bool(_), Num(_, _) | Mat(_)) => {\n                Err(IncompatibleOperands {\n                    expression: self.clone(),\n                    operand_1: a_original.clone(),\n                    operand_2: b_original.clone(),\n                })\n            }\n\n            (\n                Sum(_, _)\n                | Difference(_, _)\n                | Product(_, _)\n                | Quotient(_, _)\n                | Remainder(_, _)\n                | Power(_, _)\n                | Equal(_, _)\n                | NotEqual(_, _)\n                | LessThan(_, _)\n                | LessThanOrEqual(_, _)\n                | GreaterThan(_, _)\n                | GreaterThanOrEqual(_, _),\n                Num(a, a_representation),\n                Num(b, b_representation),\n            ) => {\n                let representation = a_representation.merge(b_representation);\n\n                match self {\n                    Sum(_, _) => Ok(Complex(a + b, representation)),\n                    Difference(_, _) => Ok(Complex(a - b, representation)),\n                    Product(_, _) => Ok(Complex(a * b, representation)),\n                    Quotient(_, _) | Remainder(_, _) => {\n                        if b.is_zero() {\n                            Err(DivisionByZero {\n                                expression: self.clone(),\n                                dividend: a_original.clone(),\n                                divisor: b_original.clone(),\n                            })\n                        } else {\n                            Ok(Complex(\n                                match self {\n                                    Quotient(_, _) => a / b,\n                                    Remainder(_, _) => a % b,\n                                    _ => unreachable!(),\n                                },\n                                representation,\n                            ))\n                        }\n                    }\n                    Power(_, _) => {\n                        if a.is_zero() && b.is_zero() {\n                            Err(ZeroToThePowerOfZero {\n                                expression: self.clone(),\n                                base: a_original.clone(),\n                                exponent: b_original.clone(),\n                            })\n                        } else if let Some(b) = b.to_i32() {\n                            Ok(Complex(a.powi(b), representation))\n                        } else {\n                            // TODO\n                            Ok(Power(\n                                Box::new(a_evaluated.clone()),\n                                Box::new(b_evaluated.clone()),\n                            ))\n                        }\n                    }\n                    Equal(_, _) => Ok(Boolean(a == b)),\n                    NotEqual(_, _) => Ok(Boolean(a != b)),\n                    LessThan(_, _)\n                    | LessThanOrEqual(_, _)\n                    | GreaterThan(_, _)\n                    | GreaterThanOrEqual(_, _) => {\n                        if !a.im.is_zero() {\n                            Err(InvalidOperand {\n                                expression: self.clone(),\n                                operand: a_original.clone(),\n                            })\n                        } else if !b.im.is_zero() {\n                            Err(InvalidOperand {\n                                expression: self.clone(),\n                                operand: b_original.clone(),\n                            })\n                        } else {\n                            let a = a.re;\n                            let b = b.re;\n\n                            Ok(Boolean(match self {\n                                LessThan(_, _) => a < b,\n                                LessThanOrEqual(_, _) => a <= b,\n                                GreaterThan(_, _) => a > b,\n                                GreaterThanOrEqual(_, _) => a >= b,\n                                _ => unreachable!(),\n                            }))\n                        }\n                    }\n                    _ => unreachable!(),\n                }\n            }\n\n            (Sum(_, _) | Difference(_, _), Mat(a), Mat(b)) => {\n                if a.shape() == b.shape() {\n                    Ok(Matrix(match self {\n                        Sum(_, _) => a + b,\n                        Difference(_, _) => a - b,\n                        _ => unreachable!(),\n                    }))\n                } else {\n                    Err(IncompatibleOperands {\n                        expression: self.clone(),\n                        operand_1: a_original.clone(),\n                        operand_2: b_original.clone(),\n                    })\n                }\n            }\n\n            (Product(_, _), Mat(a), Mat(b)) => {\n                if a.is_empty() && b.is_empty() {\n                    Ok(Matrix(a))\n                } else if !a.is_empty() && !b.is_empty() && a.ncols() == b.nrows() {\n                    Ok(Matrix(crate::expression::Matrix::from_fn(\n                        a.nrows(),\n                        b.ncols(),\n                        |i, j| {\n                            (0..a.ncols())\n                                .map(|k| a[(i, k)].clone() * b[(k, j)].clone())\n                                .reduce(|a, b| a + b)\n                                .unwrap()\n                        },\n                    )))\n                } else {\n                    Err(IncompatibleOperands {\n                        expression: self.clone(),\n                        operand_1: a_original.clone(),\n                        operand_2: b_original.clone(),\n                    })\n                }\n            }\n\n            (Product(_, _), Mat(a), _) => Ok(Matrix(a.map(|element| element * b.clone()))),\n            (Product(_, _), _, Mat(b)) => Ok(Matrix(b.map(|element| a.clone() * element))),\n\n            (Equal(_, _), Bool(Some(a)), Bool(Some(b))) => Ok(Boolean(a == b)),\n            (NotEqual(_, _), Bool(Some(a)), Bool(Some(b))) => Ok(Boolean(a != b)),\n            (And(_, _), Bool(Some(a)), Bool(Some(b))) => Ok(Boolean(a && b)),\n            (Or(_, _), Bool(Some(a)), Bool(Some(b))) => Ok(Boolean(a || b)),\n\n            (Sum(_, _), _, _) => Ok(Sum(Box::new(a), Box::new(b))), // TODO\n            (Difference(_, _), _, _) => Ok(Difference(Box::new(a), Box::new(b))), // TODO\n            (Product(_, _), _, _) => Ok(Product(Box::new(a), Box::new(b))), // TODO\n            (Quotient(_, _), _, _) => Ok(Quotient(Box::new(a), Box::new(b))), // TODO\n            (Remainder(_, _), _, _) => Ok(Remainder(Box::new(a), Box::new(b))), // TODO\n            (Power(_, _), _, _) => Ok(Power(Box::new(a), Box::new(b))), // TODO\n            (Equal(_, _), _, _) => Ok(Equal(Box::new(a), Box::new(b))), // TODO\n            (NotEqual(_, _), _, _) => Ok(NotEqual(Box::new(a), Box::new(b))), // TODO\n            (LessThan(_, _), _, _) => Ok(LessThan(Box::new(a), Box::new(b))), // TODO\n            (LessThanOrEqual(_, _), _, _) => Ok(LessThanOrEqual(Box::new(a), Box::new(b))), // TODO\n            (GreaterThan(_, _), _, _) => Ok(GreaterThan(Box::new(a), Box::new(b))), // TODO\n            (GreaterThanOrEqual(_, _), _, _) => Ok(GreaterThanOrEqual(Box::new(a), Box::new(b))), // TODO\n            (And(_, _), _, _) => Ok(And(Box::new(a), Box::new(b))), // TODO\n            (Or(_, _), _, _) => Ok(Or(Box::new(a), Box::new(b))),   // TODO\n\n            (\n                Variable(_)\n                | Function(_, _)\n                | FunctionValue(_, _)\n                | Integer(_)\n                | Rational(_, _)\n                | Complex(_, _)\n                | Vector(_)\n                | VectorElement(_, _)\n                | Matrix(_)\n                | MatrixElement(_, _, _)\n                | Boolean(_)\n                | Negation(_)\n                | Not(_),\n                _,\n                _,\n            ) => unreachable!(),\n        }\n    }\n\n    /// Returns the result of performing a single evaluation step on the expression,\n    /// or an error if the expression cannot be evaluated. The `context` argument\n    /// can be used to set the values of variables by their identifiers.\n    fn evaluate_step(&self, context: &HashMap<String, Self>) -> Result<Self, Error> {\n        use crate::expression::Expression::*;\n        use crate::expression::Type::{\n            Boolean as Bool, Function as Fun, Matrix as Mat, Number as Num,\n        };\n        use Error::*;\n\n        let expression = self.simplify();\n\n        match &expression {\n            Variable(identifier) => context\n                .get(identifier)\n                .map_or_else(|| Ok(expression), |x| x.evaluate_step(context)),\n            Function(_, _) => Ok(expression),\n            FunctionValue(function, arguments) => {\n                let function_original = function;\n\n                let function = function.evaluate_step(context)?;\n\n                let mut arguments_evaluated = Vec::new();\n\n                for argument in arguments {\n                    arguments_evaluated.push(argument.evaluate_step(context)?);\n                }\n\n                match function.typ() {\n                    Num(_, _) | Mat(_) | Bool(_) => Err(InvalidOperand {\n                        expression: expression.clone(),\n                        operand: *function_original.clone(),\n                    }),\n\n                    Fun(_, f) => f(&expression, &arguments_evaluated, context),\n\n                    _ => Ok(FunctionValue(Box::new(function), arguments_evaluated)),\n                }\n            }\n            Integer(_) => Ok(expression),\n            Rational(x, _) => Ok(if x.denom().is_one() {\n                Integer(x.numer().clone())\n            } else {\n                expression\n            }),\n            Complex(z, representation) => Ok(if z.im.is_zero() {\n                Rational(z.re.clone(), *representation)\n            } else {\n                expression\n            }),\n            Vector(v) => {\n                let mut elements = Vec::new();\n\n                for element in v.iter() {\n                    elements.push(element.evaluate_step(context)?);\n                }\n\n                Ok(Vector(crate::expression::Vector::from_vec(elements)))\n            }\n            VectorElement(vector, i) => {\n                let vector_original = vector;\n                let i_original = i;\n\n                let vector = vector.evaluate_step(context)?;\n                let i = i.evaluate_step(context)?;\n\n                match (vector.typ(), i.typ()) {\n                    (Num(_, _) | Bool(_), _) => Err(InvalidOperand {\n                        expression: expression.clone(),\n                        operand: *vector_original.clone(),\n                    }),\n\n                    (_, Mat(_) | Bool(_)) => Err(InvalidOperand {\n                        expression: expression.clone(),\n                        operand: *i_original.clone(),\n                    }),\n\n                    (Mat(vector), Num(i, _)) => {\n                        if vector.ncols() != 1 {\n                            Err(InvalidOperand {\n                                expression: expression.clone(),\n                                operand: *vector_original.clone(),\n                            })\n                        } else if let Some(i) = i.to_usize() {\n                            if i >= vector.nrows() {\n                                Err(IndexOutOfBounds {\n                                    expression: expression.clone(),\n                                    vector_or_matrix: *vector_original.clone(),\n                                    index: *i_original.clone(),\n                                })\n                            } else {\n                                Ok(vector[(i, 0)].clone())\n                            }\n                        } else {\n                            Err(InvalidOperand {\n                                expression: expression.clone(),\n                                operand: *i_original.clone(),\n                            })\n                        }\n                    }\n\n                    _ => Ok(VectorElement(Box::new(vector), Box::new(i))),\n                }\n            }\n            Matrix(m) => {\n                let mut columns = Vec::new();\n\n                for column in m.column_iter() {\n                    let mut elements = Vec::new();\n\n                    for element in column.iter() {\n                        elements.push(element.evaluate_step(context)?);\n                    }\n\n                    columns.push(crate::expression::Vector::from_vec(elements));\n                }\n\n                Ok(if columns.is_empty() {\n                    Vector(crate::expression::Vector::from_vec(Vec::new()))\n                } else if columns.len() == 1 {\n                    Vector(columns.remove(0))\n                } else {\n                    Matrix(crate::expression::Matrix::from_columns(&columns))\n                })\n            }\n            MatrixElement(matrix, i, j) => {\n                let matrix_original = matrix;\n                let i_original = i;\n                let j_original = j;\n\n                let matrix = matrix.evaluate_step(context)?;\n                let i = i.evaluate_step(context)?;\n                let j = j.evaluate_step(context)?;\n\n                match (matrix.typ(), i.typ(), j.typ()) {\n                    (Num(_, _) | Bool(_), _, _) => Err(InvalidOperand {\n                        expression: expression.clone(),\n                        operand: *matrix_original.clone(),\n                    }),\n\n                    (_, Mat(_) | Bool(_), _) => Err(InvalidOperand {\n                        expression: expression.clone(),\n                        operand: *i_original.clone(),\n                    }),\n\n                    (_, _, Mat(_) | Bool(_)) => Err(InvalidOperand {\n                        expression: expression.clone(),\n                        operand: *j_original.clone(),\n                    }),\n\n                    (Mat(matrix), Num(i, _), Num(j, _)) => {\n                        if let Some(i) = i.to_usize() {\n                            if let Some(j) = j.to_usize() {\n                                if i >= matrix.nrows() {\n                                    Err(IndexOutOfBounds {\n                                        expression: expression.clone(),\n                                        vector_or_matrix: *matrix_original.clone(),\n                                        index: *i_original.clone(),\n                                    })\n                                } else if j >= matrix.ncols() {\n                                    Err(IndexOutOfBounds {\n                                        expression: expression.clone(),\n                                        vector_or_matrix: *matrix_original.clone(),\n                                        index: *j_original.clone(),\n                                    })\n                                } else {\n                                    Ok(matrix[(i, j)].clone())\n                                }\n                            } else {\n                                Err(InvalidOperand {\n                                    expression: expression.clone(),\n                                    operand: *j_original.clone(),\n                                })\n                            }\n                        } else {\n                            Err(InvalidOperand {\n                                expression: expression.clone(),\n                                operand: *i_original.clone(),\n                            })\n                        }\n                    }\n\n                    _ => Ok(MatrixElement(Box::new(matrix), Box::new(i), Box::new(j))),\n                }\n            }\n            Boolean(_) => Ok(expression),\n            Negation(a) => expression.evaluate_step_unary(a, context),\n            Not(a) => expression.evaluate_step_unary(a, context),\n            Sum(a, b) => expression.evaluate_step_binary(a, b, context),\n            Difference(a, b) => expression.evaluate_step_binary(a, b, context),\n            Product(a, b) => expression.evaluate_step_binary(a, b, context),\n            Quotient(a, b) => expression.evaluate_step_binary(a, b, context),\n            Remainder(a, b) => expression.evaluate_step_binary(a, b, context),\n            Power(a, b) => expression.evaluate_step_binary(a, b, context),\n            Equal(a, b) => expression.evaluate_step_binary(a, b, context),\n            NotEqual(a, b) => expression.evaluate_step_binary(a, b, context),\n            LessThan(a, b) => expression.evaluate_step_binary(a, b, context),\n            LessThanOrEqual(a, b) => expression.evaluate_step_binary(a, b, context),\n            GreaterThan(a, b) => expression.evaluate_step_binary(a, b, context),\n            GreaterThanOrEqual(a, b) => expression.evaluate_step_binary(a, b, context),\n            And(a, b) => expression.evaluate_step_binary(a, b, context),\n            Or(a, b) => expression.evaluate_step_binary(a, b, context),\n        }\n    }\n\n    /// Returns the result of evaluating the expression, or an error\n    /// if the expression cannot be evaluated. The `context` argument\n    /// can be used to set the values of variables by their identifiers.\n    pub fn evaluate(&self, context: &HashMap<String, Self>) -> Result<Self, Error> {\n        let mut old_expression: Self = self.clone();\n\n        loop {\n            let new_expression = old_expression.evaluate_step(context)?;\n\n            if new_expression == old_expression {\n                return Ok(new_expression);\n            }\n\n            old_expression = new_expression;\n        }\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use crate::evaluate::default_context;\n    use crate::expression::Expression;\n\n    #[track_caller]\n    fn t(expression: &str, result: &str) {\n        assert_eq!(\n            expression\n                .parse::<Expression>()\n                .unwrap()\n                .evaluate(&default_context())\n                .unwrap()\n                .to_string(),\n            result,\n        );\n    }\n\n    #[test]\n    fn arithmetic() {\n        t(\"-(-1)\", \"1\");\n        t(\"-0\", \"0\");\n\n        t(\"1 + 2\", \"3\");\n        t(\"1 + -1\", \"0\");\n        t(\"1/2 + 0.5\", \"1\");\n        t(\n            \"123456789987654321 + 987654321123456789\",\n            \"1111111111111111110\",\n        );\n\n        t(\"1 - 2\", \"-1\");\n        t(\"1 - -1\", \"2\");\n        t(\"1/2 - 0.5\", \"0\");\n        t(\n            \"123456789987654321 - 987654321123456789\",\n            \"-864197531135802468\",\n        );\n\n        t(\"1 * 2\", \"2\");\n        t(\"1 * -1\", \"-1\");\n        t(\"1/2 * 0.5\", \"0.25\");\n        t(\n            \"123456789987654321 * 987654321123456789\",\n            \"121932632103337905662094193112635269\",\n        );\n\n        t(\"1 / 2\", \"1/2\");\n        t(\"1 / -1\", \"-1\");\n        t(\"1/2 / 0.5\", \"1\");\n        t(\n            \"123456789987654321 / 987654321123456789\",\n            \"101010101/808080809\",\n        );\n\n        t(\"4 % 2\", \"0\");\n        t(\"0 % 2\", \"0\");\n        t(\"5 % 2\", \"1\");\n        t(\"-5 % 2\", \"-1\");\n        t(\"-5 % -2\", \"-1\");\n        t(\"0.75 % (1/4)\", \"0\");\n        t(\"0.75 % (1/3)\", \"1/12\");\n        t(\"987654321123456789 % 123456789987654321\", \"1222222221\");\n\n        t(\"i ^ 2\", \"-1\");\n        t(\"2 ^ 3\", \"8\");\n        t(\"2 ^ (-3)\", \"1/8\");\n        t(\"-2 ^ 4\", \"-16\");\n        t(\"(-2) ^ 4\", \"16\");\n        t(\"0.5 ^ 4\", \"0.0625\");\n        t(\n            \"987654321123456789 ^ 5\",\n            \"939777062588963894467852986656442266299580252508947542802086985660852317355013741720482949\",\n        );\n        t(\n            \"3 ^ 4 ^ 5\",\n            \"373391848741020043532959754184866588225409776783734007750636931722079040617265251229993688938803977220468765065431475158108727054592160858581351336982809187314191748594262580938807019951956404285571818041046681288797402925517668012340617298396574731619152386723046235125934896058590588284654793540505936202376547807442730582144527058988756251452817793413352141920744623027518729185432862375737063985485319476416926263819972887006907013899256524297198527698749274196276811060702333710356481\",\n        );\n    }\n\n    #[test]\n    fn linear_algebra() {\n        t(\"[1] + [2]\", \"[3]\");\n        t(\"[1] - [2]\", \"[-1]\");\n        t(\"[1] * [2]\", \"[2]\");\n        t(\"[1] * 2\", \"[2]\");\n        t(\"1 * [2]\", \"[2]\");\n\n        t(\"[1, 2] + [3, 4]\", \"[4, 6]\");\n        t(\"[1, 2] - [3, 4]\", \"[-2, -2]\");\n        t(\"[1, 2] * [[3, 4]]\", \"[[3, 4], [6, 8]]\");\n        t(\"[[1, 2]] * [3, 4]\", \"[11]\");\n        t(\"2 * [3, 4]\", \"[6, 8]\");\n        t(\"[2, 3] * 4\", \"[8, 12]\");\n\n        t(\n            \"[[a, b], [c, d], [e, f]] * [[5, 6], [7, 8]]\",\n            \"[[a * 5 + b * 7, a * 6 + b * 8], [c * 5 + d * 7, c * 6 + d * 8], [e * 5 + f * 7, e * 6 + f * 8]]\",\n        );\n    }\n\n    #[test]\n    fn indices() {\n        t(\"[a][0]\", \"a\");\n        t(\"[a, b, c][2]\", \"c\");\n        t(\"[1 + 2, 2 + 3, 3 + 4, 4 + 5][1 + 2]\", \"9\");\n\n        t(\"[[a]][0, 0]\", \"a\");\n        t(\"[[a, b, c], [d, e, f]][1, 2]\", \"f\");\n        t(\"[[1 + 2, 2 + 3], [3 + 4, 4 + 5]][0 + 0, 0 + 1]\", \"5\");\n    }\n\n    #[test]\n    fn logic() {\n        t(\"!true\", \"false\");\n        t(\"!false\", \"true\");\n\n        t(\"true && true\", \"true\");\n        t(\"true && false\", \"false\");\n        t(\"false && true\", \"false\");\n        t(\"false && false\", \"false\");\n\n        t(\"true || true\", \"true\");\n        t(\"true || false\", \"true\");\n        t(\"false || true\", \"true\");\n        t(\"false || false\", \"false\");\n    }\n\n    #[test]\n    fn comparisons() {\n        t(\"0 == 0\", \"true\");\n        t(\"0 == 0.0\", \"true\");\n        t(\"0.5 == 1/2\", \"true\");\n        t(\"1/2 == 2/4\", \"true\");\n        t(\"3 ^ 4 ^ 5 == 5 ^ 4 ^ 3\", \"false\");\n\n        t(\"0 != 0\", \"false\");\n        t(\"0 != 0.0\", \"false\");\n        t(\"0.5 != 1/2\", \"false\");\n        t(\"1/2 != 2/4\", \"false\");\n        t(\"3 ^ 4 ^ 5 != 5 ^ 4 ^ 3\", \"true\");\n\n        t(\"0 < 0\", \"false\");\n        t(\"0 < 0.0\", \"false\");\n        t(\"0.5 < 1/2\", \"false\");\n        t(\"1/2 < 2/4\", \"false\");\n        t(\"3 ^ 4 ^ 5 < 5 ^ 4 ^ 3\", \"false\");\n\n        t(\"0 <= 0\", \"true\");\n        t(\"0 <= 0.0\", \"true\");\n        t(\"0.5 <= 1/2\", \"true\");\n        t(\"1/2 <= 2/4\", \"true\");\n        t(\"3 ^ 4 ^ 5 <= 5 ^ 4 ^ 3\", \"false\");\n\n        t(\"0 > 0\", \"false\");\n        t(\"0 > 0.0\", \"false\");\n        t(\"0.5 > 1/2\", \"false\");\n        t(\"1/2 > 2/4\", \"false\");\n        t(\"3 ^ 4 ^ 5 > 5 ^ 4 ^ 3\", \"true\");\n\n        t(\"0 >= 0\", \"true\");\n        t(\"0 >= 0.0\", \"true\");\n        t(\"0.5 >= 1/2\", \"true\");\n        t(\"1/2 >= 2/4\", \"true\");\n        t(\"3 ^ 4 ^ 5 >= 5 ^ 4 ^ 3\", \"true\");\n\n        t(\"true == true\", \"true\");\n        t(\"true == false\", \"false\");\n        t(\"false == true\", \"false\");\n        t(\"false == false\", \"true\");\n\n        t(\"true != true\", \"false\");\n        t(\"true != false\", \"true\");\n        t(\"false != true\", \"true\");\n        t(\"false != false\", \"false\");\n    }\n}\n"
  },
  {
    "path": "savage_core/src/expression.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse std::{\n    collections::{HashMap, HashSet},\n    rc::Rc,\n};\n\nuse derivative::*;\nuse num::{Signed, Zero};\n\nuse crate::evaluate::Error;\n\n/// Function implementation.\npub type Function =\n    dyn Fn(&Expression, &[Expression], &HashMap<String, Expression>) -> Result<Expression, Error>;\n\n/// Arbitrary-precision integer.\npub type Integer = num::bigint::BigInt;\n\n/// Arbitrary-precision rational number.\npub type Rational = num::rational::Ratio<Integer>;\n\n/// Arbitrary-precision complex number (i.e. real and imaginary parts are arbitrary-precision rational numbers).\npub type Complex = num::complex::Complex<Rational>;\n\n/// Column vector with expressions as components.\npub type Vector = nalgebra::DVector<Expression>;\n\n/// Column-major matrix with expressions as components.\npub type Matrix = nalgebra::DMatrix<Expression>;\n\n/// Preferred representation when printing a rational number.\n#[derive(PartialEq, Eq, Clone, Copy, Debug)]\npub enum RationalRepresentation {\n    /// Fraction (numerator/denominator).\n    Fraction,\n    /// Decimal, falling back to fraction representation\n    /// if the number cannot be represented as a finite decimal.\n    Decimal,\n}\n\nimpl RationalRepresentation {\n    /// Returns the preferred representation for the result of an operation\n    /// on two numbers with representations `self` and `other`.\n    pub(crate) fn merge(self, other: Self) -> Self {\n        use RationalRepresentation::*;\n\n        if self == Decimal || other == Decimal {\n            Decimal\n        } else {\n            Fraction\n        }\n    }\n}\n\n/// Symbolic expression.\n#[derive(Derivative)]\n#[derivative(PartialEq, Eq, Clone, Debug)]\npub enum Expression {\n    /// Variable with identifier.\n    Variable(String),\n    /// Function with identifier and implementation.\n    Function(\n        String,\n        #[derivative(PartialEq = \"ignore\", Debug = \"ignore\")] Rc<Function>,\n    ),\n    /// Value of a function expression at the given arguments.\n    FunctionValue(Box<Self>, Vec<Self>),\n    /// Integer.\n    Integer(Integer),\n    /// Rational number with preferred representation.\n    Rational(Rational, RationalRepresentation),\n    /// Complex number with preferred representation for real and imaginary parts.\n    Complex(Complex, RationalRepresentation),\n    /// Column vector.\n    Vector(Vector),\n    /// Element of a column vector expression given by an index expression.\n    VectorElement(Box<Self>, Box<Self>),\n    /// Column-major matrix.\n    Matrix(Matrix),\n    /// Element of a column-major matrix expression given by row and column index expressions.\n    MatrixElement(Box<Self>, Box<Self>, Box<Self>),\n    /// Boolean value.\n    Boolean(bool),\n    /// Arithmetic negation of an expression.\n    Negation(Box<Self>),\n    /// Logical negation (NOT) of an expression.\n    Not(Box<Self>),\n    /// Sum of two expressions.\n    Sum(Box<Self>, Box<Self>),\n    /// Difference of two expressions.\n    Difference(Box<Self>, Box<Self>),\n    /// Product of two expressions.\n    Product(Box<Self>, Box<Self>),\n    /// Quotient of two expressions.\n    Quotient(Box<Self>, Box<Self>),\n    /// Remainder of the Euclidean division of the first expression by the second.\n    Remainder(Box<Self>, Box<Self>),\n    /// The first expression raised to the power of the second.\n    Power(Box<Self>, Box<Self>),\n    /// Whether two expressions are equal.\n    Equal(Box<Self>, Box<Self>),\n    /// Whether two expressions are not equal.\n    NotEqual(Box<Self>, Box<Self>),\n    /// Whether the first expression is less than the second.\n    LessThan(Box<Self>, Box<Self>),\n    /// Whether the first expression is less than or equal to the second.\n    LessThanOrEqual(Box<Self>, Box<Self>),\n    /// Whether the first expression is greater than the second.\n    GreaterThan(Box<Self>, Box<Self>),\n    /// Whether the first expression is greater than or equal to the second.\n    GreaterThanOrEqual(Box<Self>, Box<Self>),\n    /// Logical conjunction (AND) of two expressions.\n    And(Box<Self>, Box<Self>),\n    /// Logical disjunction (OR) of two expressions.\n    Or(Box<Self>, Box<Self>),\n}\n\n/// Basic expression type designed to make evaluating expressions easier.\n#[derive(Derivative)]\n#[derivative(PartialEq, Eq, Clone, Debug)]\npub(crate) enum Type {\n    /// Function with identifier and implementation.\n    Function(\n        String,\n        #[derivative(PartialEq = \"ignore\", Debug = \"ignore\")] Rc<Function>,\n    ),\n    /// Number with preferred representation for rational parts.\n    Number(Complex, RationalRepresentation),\n    /// Column-major matrix.\n    Matrix(Matrix),\n    /// Boolean expression with value (if available).\n    Boolean(Option<bool>),\n    /// Arithmetic expression (in particular, this expression does *not* have a boolean value).\n    Arithmetic,\n    /// Expression that cannot be assigned to any of the above types with certainty.\n    Unknown,\n}\n\n/// Associativity of an operator expression.\n#[allow(clippy::enum_variant_names)]\n#[derive(PartialEq, Eq, Clone, Copy, Debug)]\npub(crate) enum Associativity {\n    /// `a OP b OP c == (a OP b) OP c`.\n    LeftAssociative,\n    /// `a OP b OP c == a OP (b OP c)`.\n    RightAssociative,\n    /// `a OP b OP c == (a OP b) OP c == a OP (b OP c)`.\n    Associative,\n}\n\nimpl Expression {\n    /// Returns the basic type of the expression.\n    pub(crate) fn typ(&self) -> Type {\n        use Expression::*;\n        use RationalRepresentation::*;\n        use Type::{\n            Arithmetic, Boolean as Bool, Function as Fun, Matrix as Mat, Number as Num, Unknown,\n        };\n\n        match self {\n            Variable(_) => Unknown,\n            Function(identifier, f) => Fun(identifier.clone(), f.clone()),\n            FunctionValue(_, _) => Unknown,\n            Integer(n) => Num(self::Rational::from_integer(n.clone()).into(), Fraction),\n            Rational(x, representation) => Num(x.into(), *representation),\n            Complex(z, representation) => Num(z.clone(), *representation),\n            Vector(v) => Mat(self::Matrix::from_columns(&[v.clone()])),\n            VectorElement(_, _) => Unknown,\n            Matrix(m) => Mat(m.clone()),\n            MatrixElement(_, _, _) => Unknown,\n            Boolean(boolean) => Bool(Some(*boolean)),\n            Negation(_) => Arithmetic,\n            Not(_) => Bool(None),\n            Sum(_, _) => Arithmetic,\n            Difference(_, _) => Arithmetic,\n            Product(_, _) => Arithmetic,\n            Quotient(_, _) => Arithmetic,\n            Remainder(_, _) => Arithmetic,\n            Power(_, _) => Arithmetic,\n            Equal(_, _) => Bool(None),\n            NotEqual(_, _) => Bool(None),\n            LessThan(_, _) => Bool(None),\n            LessThanOrEqual(_, _) => Bool(None),\n            GreaterThan(_, _) => Bool(None),\n            GreaterThanOrEqual(_, _) => Bool(None),\n            And(_, _) => Bool(None),\n            Or(_, _) => Bool(None),\n        }\n    }\n\n    /// Returns the precedence (as an integer intended for comparison)\n    /// and associativity of the expression. For unary or non-operator\n    /// expressions, to which the concept of associativity doesn't apply,\n    /// `Associative` is returned.\n    pub(crate) fn precedence_and_associativity(&self) -> (isize, Associativity) {\n        use Associativity::*;\n        use Expression::*;\n\n        match self {\n            Variable(_) => (isize::MAX, Associative),\n            Function(_, _) => (isize::MAX, Associative),\n            FunctionValue(_, _) => (5, Associative),\n            Integer(n) => {\n                if n.is_negative() {\n                    (2, Associative)\n                } else {\n                    (isize::MAX, Associative)\n                }\n            }\n            Rational(x, _) => {\n                if self.to_string().contains('/') {\n                    (2, LeftAssociative)\n                } else if x.is_negative() {\n                    (2, Associative)\n                } else {\n                    (isize::MAX, Associative)\n                }\n            }\n            Complex(z, _) => {\n                if !z.re.is_zero() && !z.im.is_zero() {\n                    if self.to_string().contains('+') {\n                        (1, Associative)\n                    } else {\n                        (1, LeftAssociative)\n                    }\n                } else if self.to_string().contains('/') {\n                    (2, LeftAssociative)\n                } else if z.re.is_negative() || !z.im.is_zero() {\n                    (2, Associative)\n                } else {\n                    (isize::MAX, Associative)\n                }\n            }\n            Vector(_) => (isize::MAX, Associative),\n            VectorElement(_, _) => (5, Associative),\n            Matrix(_) => (isize::MAX, Associative),\n            MatrixElement(_, _, _) => (5, Associative),\n            Boolean(_) => (isize::MAX, Associative),\n            Negation(_) => (3, Associative),\n            Not(_) => (3, Associative),\n            Sum(_, _) => (1, Associative),\n            Difference(_, _) => (1, LeftAssociative),\n            Product(_, _) => (2, Associative),\n            Quotient(_, _) => (2, LeftAssociative),\n            Remainder(_, _) => (2, LeftAssociative),\n            Power(_, _) => (4, RightAssociative),\n            Equal(_, _) => (0, Associative),\n            NotEqual(_, _) => (0, Associative),\n            LessThan(_, _) => (0, Associative),\n            LessThanOrEqual(_, _) => (0, Associative),\n            GreaterThan(_, _) => (0, Associative),\n            GreaterThanOrEqual(_, _) => (0, Associative),\n            And(_, _) => (-1, Associative),\n            Or(_, _) => (-2, Associative),\n        }\n    }\n\n    /// Returns the precedence (as an integer intended for comparison) of the expression.\n    pub(crate) fn precedence(&self) -> isize {\n        self.precedence_and_associativity().0\n    }\n\n    /// Returns the associativity of the expression.\n    /// For unary or non-operator expressions, to which the concept\n    /// of associativity doesn't apply, `Associative` is returned.\n    pub(crate) fn associativity(&self) -> Associativity {\n        self.precedence_and_associativity().1\n    }\n\n    /// Returns all sub-expressions that the expression contains.\n    /// The returned list is built recursively and thus includes sub-expressions\n    /// of sub-expressions and so on, as well as the expression itself.\n    pub(crate) fn parts(&self) -> Vec<Self> {\n        use Expression::*;\n\n        let mut parts = vec![self.clone()];\n\n        match self {\n            Variable(_) => {}\n            Function(_, _) => {}\n            FunctionValue(function, arguments) => {\n                parts.append(&mut function.parts());\n\n                for argument in arguments {\n                    parts.append(&mut argument.parts());\n                }\n            }\n            Integer(_) => {}\n            Rational(_, _) => {}\n            Complex(_, _) => {}\n            Vector(v) => {\n                for element in v.iter() {\n                    parts.append(&mut element.parts());\n                }\n            }\n            VectorElement(vector, i) => {\n                parts.append(&mut vector.parts());\n                parts.append(&mut i.parts());\n            }\n            Matrix(m) => {\n                for element in m.iter() {\n                    parts.append(&mut element.parts());\n                }\n            }\n            MatrixElement(matrix, i, j) => {\n                parts.append(&mut matrix.parts());\n                parts.append(&mut i.parts());\n                parts.append(&mut j.parts());\n            }\n            Boolean(_) => {}\n            Negation(a) | Not(a) => {\n                parts.append(&mut a.parts());\n            }\n            Sum(a, b)\n            | Difference(a, b)\n            | Product(a, b)\n            | Quotient(a, b)\n            | Remainder(a, b)\n            | Power(a, b)\n            | Equal(a, b)\n            | NotEqual(a, b)\n            | LessThan(a, b)\n            | LessThanOrEqual(a, b)\n            | GreaterThan(a, b)\n            | GreaterThanOrEqual(a, b)\n            | And(a, b)\n            | Or(a, b) => {\n                parts.append(&mut a.parts());\n                parts.append(&mut b.parts());\n            }\n        }\n\n        parts\n    }\n\n    /// Returns the identifiers of all variables that the expression contains.\n    pub fn variables(&self) -> HashSet<String> {\n        let mut identifiers = HashSet::new();\n\n        for part in self.parts() {\n            if let Self::Variable(identifier) = part {\n                identifiers.insert(identifier);\n            }\n        }\n\n        identifiers\n    }\n}\n"
  },
  {
    "path": "savage_core/src/functions/combinatorics.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse num::range_inclusive;\nuse savage_macros::function;\n\nuse crate::{expression::Integer, functions::NonNegativeInteger};\n\n#[function(\n    name = \"factorial\",\n    description = \"factorial of a non-negative integer\",\n    examples = r#\"[\n        (\"factorial(0)\", \"1\"),\n        (\"factorial(1)\", \"1\"),\n        (\"factorial(4)\", \"24\"),\n        (\"factorial(10)\", \"3628800\"),\n    ]\"#,\n    categories = r#\"[\n        \"combinatorics\",\n    ]\"#\n)]\nfn factorial(n: NonNegativeInteger) -> Integer {\n    range_inclusive::<Integer>(1.into(), n).product()\n}\n"
  },
  {
    "path": "savage_core/src/functions/linear_algebra.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse permutohedron::heap_recursive;\nuse savage_macros::function;\n\nuse crate::{expression::Expression, functions::SquareMatrix, helpers::*};\n\n#[function(\n    name = \"det\",\n    description = \"determinant of a square matrix\",\n    examples = r#\"[\n        (\"det([[1, 2], [3, 4]])\", \"-2\"),\n        (\"det([[a, b], [c, d]])\", \"a * d - b * c\"),\n        (\"det([])\", \"1\"),\n    ]\"#,\n    categories = r#\"[\n        \"linear algebra\",\n    ]\"#\n)]\nfn determinant(matrix: SquareMatrix) -> Expression {\n    if matrix.is_empty() {\n        return int(1);\n    }\n\n    let mut indices = (0..matrix.nrows()).collect::<Vec<usize>>();\n\n    let mut products = Vec::new();\n\n    heap_recursive(indices.as_mut_slice(), |permutation| {\n        products.push(\n            (0..matrix.nrows())\n                .map(|i| matrix[(i, permutation[i])].clone())\n                .reduce(|a, b| a * b)\n                .unwrap(),\n        );\n    });\n\n    // The first permutation generated by Heap's algorithm is the identity,\n    // which has positive sign...\n    let mut positive = true;\n\n    products\n        .into_iter()\n        .reduce(|a, b| {\n            // ... and every following permutation differs from its predecessor\n            // by exactly one transposition, which flips the sign.\n            positive = !positive;\n\n            if positive {\n                a + b\n            } else {\n                a - b\n            }\n        })\n        .unwrap()\n}\n"
  },
  {
    "path": "savage_core/src/functions/logic.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse savage_macros::function;\n\n#[function(\n    name = \"and\",\n    description = \"logical conjunction\",\n    examples = r#\"[\n        (\"and(true, true)\", \"true\"),\n        (\"and(true, false)\", \"false\"),\n        (\"and(false, true)\", \"false\"),\n        (\"and(false, false)\", \"false\"),\n    ]\"#,\n    categories = r#\"[\n        \"logic\",\n        \"boolean operators\",\n    ]\"#\n)]\nfn and(a: bool, b: bool) -> bool {\n    a && b\n}\n"
  },
  {
    "path": "savage_core/src/functions/mod.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nmod combinatorics;\nmod linear_algebra;\nmod logic;\nmod number_theory;\n\nuse std::rc::Rc;\n\nuse num::Signed;\nuse savage_macros::functions;\n\nuse crate::expression::{Expression, Function as FunctionImplementation, Integer, Matrix};\n\n/// Arbitrary-precision non-negative integer.\n/// This type alias is intended for use in function signatures\n/// to mark integer parameters that must be non-negative.\npub(crate) type NonNegativeInteger = Integer;\n\n/// Arbitrary-precision positive integer.\n/// This type alias is intended for use in function signatures\n/// to mark integer parameters that must be positive.\npub(crate) type PositiveInteger = Integer;\n\n/// Column-major square matrix with expressions as components.\n/// This type alias is intended for use in function signatures\n/// to mark matrix parameters that must be square matrices.\npub(crate) type SquareMatrix = Matrix;\n\n/// Function parameter.\n#[derive(PartialEq, Eq, Clone, Copy, Debug)]\npub enum Parameter {\n    /// Any symbolic expression.\n    Expression,\n    /// Integer expression, or an expression that can be interpreted as an integer.\n    Integer,\n    /// Non-negative integer expression, or an expression that can be interpreted as a non-negative integer.\n    NonNegativeInteger,\n    /// Positive integer expression, or an expression that can be interpreted as a positive integer.\n    PositiveInteger,\n    /// Rational number expression, or an expression that can be interpreted as a rational number.\n    Rational,\n    /// Complex number expression, or an expression that can be interpreted as a complex number.\n    Complex,\n    /// Vector expression, or an expression that can be interpreted as a vector.\n    Vector,\n    /// Matrix expression, or an expression that can be interpreted as a matrix.\n    Matrix,\n    /// Matrix expression containing a square matrix, or an expression that can be interpreted as a square matrix.\n    SquareMatrix,\n    /// Boolean expression, or an expression that can be interpreted as a boolean value.\n    Boolean,\n}\n\n/// Metadata associated with a function.\n#[derive(PartialEq, Eq, Clone, Debug)]\npub struct Metadata {\n    /// Name used to represent the function (also, default identifier for invoking the function).\n    pub name: &'static str,\n    /// Human-readable description of the function.\n    pub description: &'static str,\n    /// Parameters expected by the function, in the expected order.\n    pub parameters: &'static [Parameter],\n    /// Usage examples for the function, as pairs of REPL input and output.\n    pub examples: &'static [(&'static str, &'static str)],\n    /// Categories associated with the function.\n    pub categories: &'static [&'static str],\n}\n\n/// Function definition.\npub struct Function {\n    /// Metadata associated with the function.\n    pub metadata: Metadata,\n    /// Implementation of the function.\n    pub implementation: Rc<FunctionImplementation>,\n}\n\n/// Returns a regular function implementation that type-checks its arguments\n/// based on the given `parameters` and then invokes the given function `proxy`.\nfn wrap_proxy(\n    parameters: &'static [Parameter],\n    proxy: impl Fn(&[Expression]) -> Result<Expression, Expression> + 'static,\n) -> Rc<FunctionImplementation> {\n    use crate::evaluate::Error::*;\n    use crate::expression::Type::{Arithmetic, Boolean as Bool, Unknown};\n    use Parameter::*;\n\n    Rc::new(move |expression, arguments, _| {\n        if arguments.len() != parameters.len() {\n            return Err(InvalidNumberOfArguments {\n                expression: expression.clone(),\n                min_number: parameters.len(),\n                max_number: parameters.len(),\n                given_number: arguments.len(),\n            });\n        }\n\n        for (argument, parameter) in arguments.iter().zip(parameters) {\n            if let Bool(None) | Arithmetic | Unknown = argument.typ() {\n                if *parameter != Expression {\n                    return Ok(expression.clone());\n                }\n            }\n\n            let mut argument_valid = true;\n\n            match parameter {\n                NonNegativeInteger => {\n                    if let Ok(integer) = crate::expression::Integer::try_from(argument.clone()) {\n                        argument_valid = !integer.is_negative();\n                    }\n                }\n                PositiveInteger => {\n                    if let Ok(integer) = crate::expression::Integer::try_from(argument.clone()) {\n                        argument_valid = integer.is_positive();\n                    }\n                }\n                SquareMatrix => {\n                    if let Ok(matrix) = crate::expression::Matrix::try_from(argument.clone()) {\n                        argument_valid = matrix.is_square() || matrix.is_empty();\n                    }\n                }\n                _ => (),\n            }\n\n            if !argument_valid {\n                return Err(InvalidArgument {\n                    expression: expression.clone(),\n                    argument: argument.clone(),\n                });\n            }\n        }\n\n        proxy(arguments).map_err(|argument| InvalidArgument {\n            expression: expression.clone(),\n            argument,\n        })\n    })\n}\n\n/// Returns all available functions.\npub fn functions() -> Vec<Function> {\n    functions!(\n        logic::and,\n        combinatorics::factorial,\n        linear_algebra::determinant,\n        number_theory::is_prime,\n        number_theory::nth_prime,\n        number_theory::prime_pi,\n    )\n}\n\n/// Returns an expression representing the function with the given name,\n/// or `None` if the function library contains no function with that name.\npub fn function_expression(name: &str) -> Option<Expression> {\n    for function in functions() {\n        if function.metadata.name == name {\n            return Some(Expression::Function(\n                function.metadata.name.to_owned(),\n                function.implementation,\n            ));\n        }\n    }\n\n    None\n}\n\n#[cfg(test)]\nmod tests {\n    use crate::evaluate::default_context;\n    use crate::expression::Expression;\n    use crate::functions::functions;\n\n    #[track_caller]\n    fn t(expression: &str, result: &str) {\n        assert_eq!(\n            expression\n                .parse::<Expression>()\n                .unwrap()\n                .evaluate(&default_context())\n                .unwrap()\n                .to_string(),\n            result,\n        );\n    }\n\n    #[test]\n    fn examples() {\n        for function in functions() {\n            for (expression, result) in function.metadata.examples {\n                t(expression, result);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "savage_core/src/functions/number_theory.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse num::ToPrimitive;\nuse primal::StreamingSieve;\nuse savage_macros::function;\n\nuse crate::{\n    expression::Expression,\n    functions::{function_expression, NonNegativeInteger, PositiveInteger},\n    helpers::*,\n};\n\n#[function(\n    name = \"is_prime\",\n    description = \"whether the given non-negative integer is a prime number\",\n    examples = r#\"[\n        (\"is_prime(0)\", \"false\"),\n        (\"is_prime(1)\", \"false\"),\n        (\"is_prime(2)\", \"true\"),\n        (\"is_prime(29)\", \"true\"),\n        (\"is_prime(2^31)\", \"false\"),\n        (\"is_prime(2^31 - 1)\", \"true\"),\n    ]\"#,\n    categories = r#\"[\n        \"number theory\",\n        \"prime numbers\",\n    ]\"#\n)]\nfn is_prime(n: NonNegativeInteger) -> Expression {\n    if let Some(n) = n.to_u64() {\n        Expression::Boolean(primal::is_prime(n))\n    } else {\n        fun(function_expression(\"is_prime\").unwrap(), [int(n)])\n    }\n}\n\n#[function(\n    name = \"nth_prime\",\n    description = \"`n`th prime number, 1-indexed\",\n    examples = r#\"[\n        (\"nth_prime(1)\", \"2\"),\n        (\"nth_prime(10)\", \"29\"),\n        (\"nth_prime(100)\", \"541\"),\n        (\"nth_prime(1000)\", \"7919\"),\n    ]\"#,\n    categories = r#\"[\n        \"number theory\",\n        \"prime numbers\",\n    ]\"#\n)]\nfn nth_prime(n: PositiveInteger) -> Expression {\n    if let Some(n) = n.to_usize() {\n        int(StreamingSieve::nth_prime(n))\n    } else {\n        fun(function_expression(\"nth_prime\").unwrap(), [int(n)])\n    }\n}\n\n#[function(\n    name = \"prime_pi\",\n    description = \"number of prime numbers less than or equal to the given non-negative integer\",\n    examples = r#\"[\n        (\"prime_pi(10)\", \"4\"),\n        (\"prime_pi(100)\", \"25\"),\n        (\"prime_pi(1000)\", \"168\"),\n        (\"prime_pi(10000)\", \"1229\"),\n        (\"prime_pi(100000)\", \"9592\"),\n    ]\"#,\n    categories = r#\"[\n        \"number theory\",\n        \"prime numbers\",\n    ]\"#\n)]\nfn prime_pi(n: NonNegativeInteger) -> Expression {\n    if let Some(n) = n.to_usize() {\n        int(StreamingSieve::prime_pi(n))\n    } else {\n        fun(function_expression(\"prime_pi\").unwrap(), [int(n)])\n    }\n}\n"
  },
  {
    "path": "savage_core/src/helpers.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\n//! Operators, conversions, and helper functions to make working with expressions easier.\n\nuse std::ops::{\n    Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign,\n};\n\nuse num::{One, Zero};\n\nuse crate::expression::{\n    Complex, Expression, Integer, Matrix, Rational, RationalRepresentation, Type, Vector,\n};\n\nimpl Neg for Expression {\n    type Output = Self;\n\n    fn neg(self) -> Self {\n        Expression::Negation(Box::new(self))\n    }\n}\n\nimpl Not for Expression {\n    type Output = Self;\n\n    fn not(self) -> Self {\n        Expression::Not(Box::new(self))\n    }\n}\n\nimpl Add for Expression {\n    type Output = Self;\n\n    fn add(self, other: Self) -> Self {\n        Expression::Sum(Box::new(self), Box::new(other))\n    }\n}\n\nimpl AddAssign for Expression {\n    fn add_assign(&mut self, other: Self) {\n        *self = self.clone() + other;\n    }\n}\n\nimpl Sub for Expression {\n    type Output = Self;\n\n    fn sub(self, other: Self) -> Self {\n        Expression::Difference(Box::new(self), Box::new(other))\n    }\n}\n\nimpl SubAssign for Expression {\n    fn sub_assign(&mut self, other: Self) {\n        *self = self.clone() - other;\n    }\n}\n\nimpl Mul for Expression {\n    type Output = Self;\n\n    fn mul(self, other: Self) -> Self {\n        Expression::Product(Box::new(self), Box::new(other))\n    }\n}\n\nimpl MulAssign for Expression {\n    fn mul_assign(&mut self, other: Self) {\n        *self = self.clone() * other;\n    }\n}\n\nimpl Div for Expression {\n    type Output = Self;\n\n    fn div(self, other: Self) -> Self {\n        Expression::Quotient(Box::new(self), Box::new(other))\n    }\n}\n\nimpl DivAssign for Expression {\n    fn div_assign(&mut self, other: Self) {\n        *self = self.clone() / other;\n    }\n}\n\nimpl Rem for Expression {\n    type Output = Self;\n\n    fn rem(self, other: Self) -> Self {\n        Expression::Remainder(Box::new(self), Box::new(other))\n    }\n}\n\nimpl RemAssign for Expression {\n    fn rem_assign(&mut self, other: Self) {\n        *self = self.clone() % other;\n    }\n}\n\nimpl From<&Self> for Expression {\n    fn from(expression: &Self) -> Self {\n        expression.clone()\n    }\n}\n\nimpl From<Integer> for Expression {\n    fn from(integer: Integer) -> Self {\n        Expression::Integer(integer)\n    }\n}\n\nimpl TryFrom<Expression> for Integer {\n    type Error = Expression;\n\n    fn try_from(expression: Expression) -> Result<Self, Self::Error> {\n        if let Type::Number(z, _) = expression.typ() {\n            if z.im.is_zero() && z.re.denom().is_one() {\n                Ok(z.re.numer().clone())\n            } else {\n                Err(expression)\n            }\n        } else {\n            Err(expression)\n        }\n    }\n}\n\nimpl From<Rational> for Expression {\n    fn from(rational: Rational) -> Self {\n        Expression::Rational(rational, RationalRepresentation::Fraction)\n    }\n}\n\nimpl TryFrom<Expression> for Rational {\n    type Error = Expression;\n\n    fn try_from(expression: Expression) -> Result<Self, Self::Error> {\n        if let Type::Number(z, _) = expression.typ() {\n            if z.im.is_zero() {\n                Ok(z.re)\n            } else {\n                Err(expression)\n            }\n        } else {\n            Err(expression)\n        }\n    }\n}\n\nimpl From<Complex> for Expression {\n    fn from(complex: Complex) -> Self {\n        Expression::Complex(complex, RationalRepresentation::Fraction)\n    }\n}\n\nimpl TryFrom<Expression> for Complex {\n    type Error = Expression;\n\n    fn try_from(expression: Expression) -> Result<Self, Self::Error> {\n        if let Type::Number(z, _) = expression.typ() {\n            Ok(z)\n        } else {\n            Err(expression)\n        }\n    }\n}\n\nimpl From<Vector> for Expression {\n    fn from(vector: Vector) -> Self {\n        Expression::Vector(vector)\n    }\n}\n\nimpl TryFrom<Expression> for Vector {\n    type Error = Expression;\n\n    fn try_from(expression: Expression) -> Result<Self, Self::Error> {\n        if let Type::Matrix(m) = expression.typ() {\n            if m.ncols() == 1 {\n                Ok(m.column(0).clone_owned())\n            } else {\n                Err(expression)\n            }\n        } else {\n            Err(expression)\n        }\n    }\n}\n\nimpl From<Matrix> for Expression {\n    fn from(matrix: Matrix) -> Self {\n        Expression::Matrix(matrix)\n    }\n}\n\nimpl TryFrom<Expression> for Matrix {\n    type Error = Expression;\n\n    fn try_from(expression: Expression) -> Result<Self, Self::Error> {\n        if let Type::Matrix(m) = expression.typ() {\n            Ok(m)\n        } else {\n            Err(expression)\n        }\n    }\n}\n\nimpl From<bool> for Expression {\n    fn from(boolean: bool) -> Self {\n        Expression::Boolean(boolean)\n    }\n}\n\nimpl TryFrom<Expression> for bool {\n    type Error = Expression;\n\n    fn try_from(expression: Expression) -> Result<Self, Self::Error> {\n        if let Expression::Boolean(boolean) = expression {\n            Ok(boolean)\n        } else {\n            Err(expression)\n        }\n    }\n}\n\n/// Returns an expression representing the variable with the given identifier.\npub fn var(identifier: impl Into<String>) -> Expression {\n    Expression::Variable(identifier.into())\n}\n\n/// Returns an expression representing the value of the given function at the given arguments.\npub fn fun(function: impl Into<Expression>, arguments: impl Into<Vec<Expression>>) -> Expression {\n    Expression::FunctionValue(Box::new(function.into()), arguments.into())\n}\n\n/// Returns an expression representing the given integer.\npub fn int(integer: impl Into<Integer>) -> Expression {\n    Expression::Integer(integer.into())\n}\n\n/// Returns an expression representing the rational number with\n/// the given numerator and denominator, using fraction representation.\npub fn rat(numerator: impl Into<Integer>, denominator: impl Into<Integer>) -> Expression {\n    Expression::Rational(\n        Rational::new(numerator.into(), denominator.into()),\n        RationalRepresentation::Fraction,\n    )\n}\n\n/// Returns an expression representing the rational number with\n/// the given numerator and denominator, using decimal representation,\n/// falling back to fraction representation if the number cannot be\n/// represented as a finite decimal.\npub fn ratd(numerator: impl Into<Integer>, denominator: impl Into<Integer>) -> Expression {\n    Expression::Rational(\n        Rational::new(numerator.into(), denominator.into()),\n        RationalRepresentation::Decimal,\n    )\n}\n\n/// Returns an expression representing the complex number with\n/// real and imaginary parts being rational numbers described by\n/// the given numerators and denominators, using fraction representation.\npub fn com(\n    real_numerator: impl Into<Integer>,\n    real_denominator: impl Into<Integer>,\n    imaginary_numerator: impl Into<Integer>,\n    imaginary_denominator: impl Into<Integer>,\n) -> Expression {\n    Expression::Complex(\n        Complex::new(\n            Rational::new(real_numerator.into(), real_denominator.into()),\n            Rational::new(imaginary_numerator.into(), imaginary_denominator.into()),\n        ),\n        RationalRepresentation::Fraction,\n    )\n}\n\n/// Returns an expression representing the complex number with\n/// real and imaginary parts being rational numbers described by\n/// the given numerators and denominators, using decimal representation,\n/// falling back to fraction representation for parts that cannot be\n/// represented as a finite decimal.\npub fn comd(\n    real_numerator: impl Into<Integer>,\n    real_denominator: impl Into<Integer>,\n    imaginary_numerator: impl Into<Integer>,\n    imaginary_denominator: impl Into<Integer>,\n) -> Expression {\n    Expression::Complex(\n        Complex::new(\n            Rational::new(real_numerator.into(), real_denominator.into()),\n            Rational::new(imaginary_numerator.into(), imaginary_denominator.into()),\n        ),\n        RationalRepresentation::Decimal,\n    )\n}\n\n/// Returns an expression representing the first expression raised to the power of the second.\npub fn pow(base: impl Into<Expression>, exponent: impl Into<Expression>) -> Expression {\n    Expression::Power(Box::new(base.into()), Box::new(exponent.into()))\n}\n\n/// Returns an expression representing whether two expressions are equal.\npub fn eq(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {\n    Expression::Equal(Box::new(left.into()), Box::new(right.into()))\n}\n\n/// Returns an expression representing whether two expressions are not equal.\npub fn ne(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {\n    Expression::NotEqual(Box::new(left.into()), Box::new(right.into()))\n}\n\n/// Returns an expression representing whether the first expression is less than the second.\npub fn lt(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {\n    Expression::LessThan(Box::new(left.into()), Box::new(right.into()))\n}\n\n/// Returns an expression representing whether the first expression is less than or equal to the second.\npub fn le(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {\n    Expression::LessThanOrEqual(Box::new(left.into()), Box::new(right.into()))\n}\n\n/// Returns an expression representing whether the first expression is greater than the second.\npub fn gt(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {\n    Expression::GreaterThan(Box::new(left.into()), Box::new(right.into()))\n}\n\n/// Returns an expression representing whether the first expression is greater than or equal to the second.\npub fn ge(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {\n    Expression::GreaterThanOrEqual(Box::new(left.into()), Box::new(right.into()))\n}\n\n/// Returns an expression representing the logical conjunction (AND) of two expressions.\npub fn and(a: impl Into<Expression>, b: impl Into<Expression>) -> Expression {\n    Expression::And(Box::new(a.into()), Box::new(b.into()))\n}\n\n/// Returns an expression representing the logical disjunction (OR) of two expressions.\npub fn or(a: impl Into<Expression>, b: impl Into<Expression>) -> Expression {\n    Expression::Or(Box::new(a.into()), Box::new(b.into()))\n}\n"
  },
  {
    "path": "savage_core/src/lib.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\npub mod evaluate;\npub mod expression;\npub mod functions;\npub mod helpers;\npub mod parse;\nmod print;\nmod simplify;\n"
  },
  {
    "path": "savage_core/src/parse.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse std::{ops::Range, str::FromStr};\n\nuse chumsky::prelude::*;\n\nuse crate::{\n    expression::{Expression, Integer, Matrix, Vector},\n    helpers::*,\n};\n\n/// Error that occurred while trying to parse a character stream into an expression.\npub type Error = chumsky::error::Simple<char, Range<usize>>;\n\n/// Reason why a parse error occurred.\npub type ErrorReason = chumsky::error::SimpleReason<char, Range<usize>>;\n\n/// Returns a parser that produces expressions from character streams.\n///\n/// The purpose of this function is to be a building block for parsers that parse\n/// expressions as parts of a more complex input language. If you simply want\n/// to turn strings into expressions, use `\"a + b\".parse::<Expression>()`.\n#[allow(clippy::let_and_return)]\npub fn parser() -> impl Parser<char, Expression, Error = Error> {\n    recursive(|expression| {\n        let identifier = text::ident()\n            .map(|identifier: String| match identifier.as_str() {\n                \"true\" => Expression::Boolean(true),\n                \"false\" => Expression::Boolean(false),\n                _ => var(identifier),\n            })\n            .labelled(\"identifier\")\n            .boxed();\n\n        let number = text::int(10)\n            .chain(just('.').ignore_then(text::digits(10)).or_not())\n            .map(|parts: Vec<String>| match parts.as_slice() {\n                [integer] => int(integer.parse::<Integer>().unwrap()),\n                [integer_part, fractional_part] => {\n                    let numerator = format!(\"{}{}\", integer_part, fractional_part);\n                    let denominator = format!(\"1{}\", \"0\".repeat(fractional_part.len()));\n                    ratd(\n                        numerator.parse::<Integer>().unwrap(),\n                        denominator.parse::<Integer>().unwrap(),\n                    )\n                }\n                _ => unreachable!(),\n            })\n            .labelled(\"number\")\n            .boxed();\n\n        let vector_or_matrix = expression\n            .clone()\n            .separated_by(just(','))\n            .padded()\n            .delimited_by(just('['), just(']'))\n            .map(|elements| {\n                if let Some(Expression::Vector(v)) = elements.first() {\n                    // If all elements of the vector are themselves vectors, and have the same size,\n                    // they are interpreted as the rows of a rectangular matrix.\n                    let row_size = v.len();\n                    let mut rows = Vec::new();\n\n                    for element in &elements {\n                        match element {\n                            Expression::Vector(v) if v.len() == row_size => {\n                                rows.push(v.transpose());\n                            }\n                            _ => return Expression::Vector(Vector::from_vec(elements)),\n                        }\n                    }\n\n                    Expression::Matrix(Matrix::from_rows(&rows))\n                } else {\n                    Expression::Vector(Vector::from_vec(elements))\n                }\n            })\n            .labelled(\"vector_or_matrix\")\n            .boxed();\n\n        let atomic_expression = identifier\n            .or(number)\n            .or(vector_or_matrix)\n            .or(expression.clone().delimited_by(just('('), just(')')))\n            .padded()\n            .boxed();\n\n        let function_or_element = atomic_expression\n            .then(\n                expression\n                    .clone()\n                    .separated_by(just(','))\n                    .padded()\n                    .delimited_by(just('('), just(')'))\n                    .map(|arguments| (Some(arguments), None))\n                    .or(expression\n                        .clone()\n                        .separated_by(just(','))\n                        .at_least(1)\n                        .at_most(2)\n                        .delimited_by(just('['), just(']'))\n                        .map(|indices| (None, Some(indices))))\n                    .or_not(),\n            )\n            .map(\n                |(expression, arguments_or_indices)| match arguments_or_indices {\n                    Some((Some(arguments), None)) => fun(expression, arguments),\n                    Some((None, Some(indices))) => {\n                        if indices.len() == 1 {\n                            Expression::VectorElement(\n                                Box::new(expression),\n                                Box::new(indices[0].clone()),\n                            )\n                        } else {\n                            Expression::MatrixElement(\n                                Box::new(expression),\n                                Box::new(indices[0].clone()),\n                                Box::new(indices[1].clone()),\n                            )\n                        }\n                    }\n                    None => expression,\n                    _ => unreachable!(),\n                },\n            )\n            .padded()\n            .boxed();\n\n        let power = function_or_element\n            .separated_by(just('^'))\n            .at_least(1)\n            .map(|expressions| {\n                expressions\n                    .into_iter()\n                    .rev()\n                    .reduce(|a, b| pow(b, a))\n                    .unwrap()\n            })\n            .labelled(\"power\")\n            .boxed();\n\n        let negation = just('-')\n            .ignore_then(power.clone())\n            .map(|a| -a)\n            .or(just('!').ignore_then(power.clone()).map(|a| !a))\n            .labelled(\"negation\")\n            .or(power)\n            .padded()\n            .boxed();\n\n        let product_or_quotient_or_remainder = negation\n            .clone()\n            .then(\n                just('*')\n                    .or(just('/'))\n                    .or(just('%'))\n                    .then(negation)\n                    .repeated(),\n            )\n            .foldl(|a, (operator, b)| match operator {\n                '*' => a * b,\n                '/' => a / b,\n                '%' => a % b,\n                _ => unreachable!(),\n            })\n            .labelled(\"product_or_quotient_or_remainder\")\n            .boxed();\n\n        let sum_or_difference = product_or_quotient_or_remainder\n            .clone()\n            .then(\n                just('+')\n                    .or(just('-'))\n                    .then(product_or_quotient_or_remainder)\n                    .repeated(),\n            )\n            .foldl(|a, (operator, b)| match operator {\n                '+' => a + b,\n                '-' => a - b,\n                _ => unreachable!(),\n            })\n            .labelled(\"sum_or_difference\")\n            .boxed();\n\n        let comparison = sum_or_difference\n            .clone()\n            .then(\n                just('=')\n                    .chain(just('='))\n                    .or(just('!').chain(just('=')))\n                    .or(just('<').chain(just('=')))\n                    .or(just('<').to(vec!['<']))\n                    .or(just('>').chain(just('=')))\n                    .or(just('>').to(vec!['>']))\n                    .collect::<String>()\n                    .then(sum_or_difference)\n                    .repeated(),\n            )\n            .foldl(|a, (operator, b)| match operator.as_str() {\n                \"==\" => eq(a, b),\n                \"!=\" => ne(a, b),\n                \"<\" => lt(a, b),\n                \"<=\" => le(a, b),\n                \">\" => gt(a, b),\n                \">=\" => ge(a, b),\n                _ => unreachable!(),\n            })\n            .labelled(\"comparison\")\n            .boxed();\n\n        let conjunction = comparison\n            .clone()\n            .then(\n                just('&')\n                    .ignore_then(just('&'))\n                    .ignore_then(comparison)\n                    .repeated(),\n            )\n            .foldl(and)\n            .labelled(\"conjunction\")\n            .boxed();\n\n        let disjunction = conjunction\n            .clone()\n            .then(\n                just('|')\n                    .ignore_then(just('|'))\n                    .ignore_then(conjunction)\n                    .repeated(),\n            )\n            .foldl(or)\n            .labelled(\"disjunction\")\n            .boxed();\n\n        disjunction\n    })\n}\n\nimpl FromStr for Expression {\n    type Err = Vec<Error>;\n\n    fn from_str(string: &str) -> Result<Self, Self::Err> {\n        parser().then_ignore(end()).parse(string)\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use nalgebra::{dmatrix, dvector};\n\n    use crate::expression::{Expression, Expression::*};\n    use crate::helpers::*;\n\n    #[track_caller]\n    fn t(string: &str, expression: Expression) {\n        assert_eq!(string.parse(), Ok(expression));\n    }\n\n    #[test]\n    fn variables() {\n        t(\"a   \", var(\"a\"));\n        t(\"     A\", var(\"A\"));\n        t(\"  Named_Variable \", var(\"Named_Variable\"));\n    }\n\n    #[test]\n    fn functions() {\n        t(\" f(   )   \", fun(var(\"f\"), []));\n        t(\"f ( a) \", fun(var(\"f\"), [var(\"a\")]));\n        t(\"f( a, 1  )\", fun(var(\"f\"), [var(\"a\"), int(1)]));\n        t(\n            \" f(  g(a ),h(   b )  ) \",\n            fun(\n                var(\"f\"),\n                [fun(var(\"g\"), [var(\"a\")]), fun(var(\"h\"), [var(\"b\")])],\n            ),\n        );\n        t(\n            \" ( f ( a ) ) ( b ) \",\n            fun(fun(var(\"f\"), [var(\"a\")]), [var(\"b\")]),\n        );\n        t(\"(f +g)( a)\", fun(var(\"f\") + var(\"g\"), [var(\"a\")]));\n    }\n\n    #[test]\n    fn integers() {\n        t(\"0\", int(0));\n        t(\"  1\", int(1));\n        t(\"1234567890  \", int(1234567890));\n        t(\"  9876543210  \", int(9876543210u64));\n    }\n\n    #[test]\n    fn rational_numbers() {\n        t(\"0.5\", ratd(1, 2));\n        t(\" 1.5\", ratd(3, 2));\n        t(\"3.075 \", ratd(123, 40));\n        t(\" 100.000 \", ratd(100, 1));\n    }\n\n    #[test]\n    fn vectors() {\n        t(\" [ ] \", Vector(dvector![]));\n        t(\"[   1]\", Vector(dvector![int(1)]));\n        t(\" [1,2,   3 ]\", Vector(dvector![int(1), int(2), int(3)]));\n        t(\n            \"[  1,f(a,1),[   1,2,3  ] ]  \",\n            Vector(dvector![\n                int(1),\n                fun(var(\"f\"), [var(\"a\"), int(1)]),\n                Vector(dvector![int(1), int(2), int(3)])\n            ]),\n        );\n    }\n\n    #[test]\n    fn matrices() {\n        t(\"[[1   ]   ]   \", Matrix(dmatrix![int(1)]));\n        t(\"[ [ 1,2,3 ] ]\", Matrix(dmatrix![int(1), int(2), int(3)]));\n        t(\n            \" [[  1, 2,3 ],[ 4,5, 6]]\",\n            Matrix(dmatrix![\n                int(1), int(2), int(3);\n                int(4), int(5), int(6)\n            ]),\n        );\n        t(\n            \"  [[f ( ) ,2, [1 ] ], [[ [ 1]],3.075,6] ] \",\n            Matrix(dmatrix![\n                fun(var(\"f\"), []), int(2), Vector(dvector![int(1)]);\n                Matrix(dmatrix![int(1)]), ratd(123, 40), int(6)\n            ]),\n        );\n    }\n\n    #[test]\n    fn booleans() {\n        t(\"   true\", Boolean(true));\n        t(\"false   \", Boolean(false));\n    }\n\n    #[test]\n    fn operators() {\n        t(\"  - 1 \", -int(1));\n        t(\" - (-    1 )\", -(-int(1)));\n        t(\"!A  \", !var(\"A\"));\n        t(\" !( ! A)\", !(!var(\"A\")));\n\n        t(\"1+2    +3   \", (int(1) + int(2)) + int(3));\n        t(\" 1 +2- 3 \", (int(1) + int(2)) - int(3));\n        t(\"1  -2 +    3\", (int(1) - int(2)) + int(3));\n        t(\"1-2-3\", (int(1) - int(2)) - int(3));\n        t(\" 1-(2 + 3)\", int(1) - (int(2) + int(3)));\n        t(\"1 - (2 - 3)\", int(1) - (int(2) - int(3)));\n\n        t(\" 1 *2* 3 \", (int(1) * int(2)) * int(3));\n        t(\"1*2 / 3\", (int(1) * int(2)) / int(3));\n        t(\"1 / 2*3  \", (int(1) / int(2)) * int(3));\n        t(\"  1/2/3\", (int(1) / int(2)) / int(3));\n        t(\"1 /(  2 *3) \", int(1) / (int(2) * int(3)));\n        t(\" 1/ (2 /3)\", int(1) / (int(2) / int(3)));\n\n        t(\"(1+2)   /3 \", (int(1) + int(2)) / int(3));\n        t(\"  1/ 2 +3\", (int(1) / int(2)) + int(3));\n        t(\"1 + 2 / 3\", int(1) + (int(2) / int(3)));\n        t(\"1/ (2+3)     \", int(1) / (int(2) + int(3)));\n\n        t(\"(1 * 2)^3\", pow(int(1) * int(2), int(3)));\n        t(\"1^2 * 3 \", pow(int(1), int(2)) * int(3));\n        t(\"1*  2  ^3\", int(1) * pow(int(2), int(3)));\n        t(\" 1^( 2 * 3 )\", pow(int(1), int(2) * int(3)));\n\n        t(\" (1^2)  ^  3\", pow(pow(int(1), int(2)), int(3)));\n        t(\"1 ^2 ^3 \", pow(int(1), pow(int(2), int(3))));\n\n        // TODO: Comparison operators!\n\n        t(\"A&&B&&C\", and(and(var(\"A\"), var(\"B\")), var(\"C\")));\n        t(\"A  &&  B||C\", or(and(var(\"A\"), var(\"B\")), var(\"C\")));\n        t(\" ( A || B ) && C \", and(or(var(\"A\"), var(\"B\")), var(\"C\")));\n        t(\"A||B ||C\", or(or(var(\"A\"), var(\"B\")), var(\"C\")));\n        t(\"A&& ( B|| C)\", and(var(\"A\"), or(var(\"B\"), var(\"C\"))));\n        t(\"   A|| B &&C\", or(var(\"A\"), and(var(\"B\"), var(\"C\"))));\n    }\n\n    // TODO: Replace with a real benchmark once `#[bench]` is stable.\n    #[test]\n    fn benchmark() {\n        for depth in 0..20 {\n            t(\n                &format!(\"{}a{}\", \"(\".repeat(depth), \")\".repeat(depth)),\n                var(\"a\"),\n            );\n        }\n    }\n}\n"
  },
  {
    "path": "savage_core/src/print.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse std::cmp::max;\nuse std::fmt::{Display, Formatter, Result};\n\nuse num::{One, Signed, Zero};\n\nuse crate::expression::{Expression, Integer, Rational};\n\n/// Returns a pair of integers `(n, m)` such that `x = n / 10^m`,\n/// or `None` if no such integers exist.\nfn decimal_representation(x: &Rational) -> Option<(Integer, usize)> {\n    // https://en.wikipedia.org/wiki/Decimal_representation#Finite_decimal_representations\n    let mut denominator = x.denom().clone();\n\n    let [power_of_2, power_of_5] = [2, 5].map(|n| {\n        let mut power = 0;\n\n        while (denominator.clone() % Integer::from(n)).is_zero() {\n            denominator /= n;\n            power += 1;\n        }\n\n        power\n    });\n\n    if denominator.is_one() {\n        let multiplier = if power_of_2 < power_of_5 {\n            Integer::from(2).pow(power_of_5 - power_of_2)\n        } else {\n            Integer::from(5).pow(power_of_2 - power_of_5)\n        };\n\n        Some((x.numer() * multiplier, max(power_of_2, power_of_5) as usize))\n    } else {\n        None\n    }\n}\n\nimpl Expression {\n    /// Formats the expression as a unary prefix operator with the minimally necessary parentheses.\n    fn fmt_prefix(&self, f: &mut Formatter<'_>, symbol: &str, a: &Self) -> Result {\n        let a_needs_parentheses = a.precedence() <= self.precedence();\n\n        write!(\n            f,\n            \"{}{}{}{}\",\n            symbol,\n            if a_needs_parentheses { \"(\" } else { \"\" },\n            a,\n            if a_needs_parentheses { \")\" } else { \"\" },\n        )\n    }\n\n    /// Formats the expression as a binary infix operator with the minimally necessary parentheses.\n    fn fmt_infix(&self, f: &mut Formatter<'_>, symbol: &str, a: &Self, b: &Self) -> Result {\n        use crate::expression::Associativity::*;\n\n        let a_needs_parentheses = (a.precedence() < self.precedence())\n            || ((a.precedence() == self.precedence())\n                && (self.associativity() == RightAssociative));\n\n        let b_needs_parentheses = (b.precedence() < self.precedence())\n            || ((b.precedence() == self.precedence()) && (self.associativity() == LeftAssociative));\n\n        write!(\n            f,\n            \"{}{}{} {} {}{}{}\",\n            if a_needs_parentheses { \"(\" } else { \"\" },\n            a,\n            if a_needs_parentheses { \")\" } else { \"\" },\n            symbol,\n            if b_needs_parentheses { \"(\" } else { \"\" },\n            b,\n            if b_needs_parentheses { \")\" } else { \"\" },\n        )\n    }\n}\n\nimpl Display for Expression {\n    fn fmt(&self, f: &mut Formatter<'_>) -> Result {\n        use crate::expression::{Expression::*, RationalRepresentation::*};\n\n        match self {\n            Variable(identifier) => write!(f, \"{}\", identifier),\n            Function(identifier, _) => write!(f, \"{}\", identifier),\n            FunctionValue(function, arguments) => {\n                let function_needs_parentheses = function.precedence() < isize::MAX;\n\n                write!(\n                    f,\n                    \"{}{}{}({})\",\n                    if function_needs_parentheses { \"(\" } else { \"\" },\n                    function,\n                    if function_needs_parentheses { \")\" } else { \"\" },\n                    arguments\n                        .iter()\n                        .map(|a| a.to_string())\n                        .collect::<Vec<_>>()\n                        .join(\", \"),\n                )\n            }\n            Integer(n) => write!(f, \"{}\", n),\n            Rational(x, representation) => {\n                match representation {\n                    Fraction => write!(f, \"{}\", x),\n                    Decimal => {\n                        if let Some((mantissa, separator_position)) = decimal_representation(x) {\n                            let mut string = mantissa.abs().to_string();\n\n                            if separator_position > 0 {\n                                if separator_position > string.len() - 1 {\n                                    // Left-pad the string with enough zeros to be able\n                                    // to insert the decimal separator at the indicated position.\n                                    string = format!(\n                                        \"{}{}\",\n                                        \"0\".repeat(separator_position - (string.len() - 1)),\n                                        string,\n                                    );\n                                }\n\n                                string.insert(string.len() - separator_position, '.');\n                            }\n\n                            write!(f, \"{}{}\", if x.is_negative() { \"-\" } else { \"\" }, string)\n                        } else {\n                            // Fall back to fraction representation.\n                            write!(f, \"{}\", x)\n                        }\n                    }\n                }\n            }\n            Complex(z, representation) => {\n                if z.im.is_zero() {\n                    write!(f, \"{}\", Rational(z.re.clone(), *representation))\n                } else if z.re.is_zero() {\n                    if z.im.abs().is_one() {\n                        write!(f, \"{}i\", if z.im.is_negative() { \"-\" } else { \"\" })\n                    } else {\n                        write!(f, \"{}*i\", Rational(z.im.clone(), *representation))\n                    }\n                } else if z.re.is_negative() && z.im.is_positive() {\n                    if z.im.is_one() {\n                        write!(f, \"i - {}\", Rational(z.re.abs(), *representation))\n                    } else {\n                        write!(\n                            f,\n                            \"{}*i - {}\",\n                            Rational(z.im.clone(), *representation),\n                            Rational(z.re.abs(), *representation),\n                        )\n                    }\n                } else if z.im.abs().is_one() {\n                    write!(\n                        f,\n                        \"{} {} i\",\n                        Rational(z.re.clone(), *representation),\n                        if z.im.is_negative() { \"-\" } else { \"+\" },\n                    )\n                } else {\n                    write!(\n                        f,\n                        \"{} {} {}*i\",\n                        Rational(z.re.clone(), *representation),\n                        if z.im.is_negative() { \"-\" } else { \"+\" },\n                        Rational(z.im.abs(), *representation),\n                    )\n                }\n            }\n            Vector(v) => write!(\n                f,\n                \"[{}]\",\n                v.iter()\n                    .map(|element| element.to_string())\n                    .collect::<Vec<_>>()\n                    .join(\", \"),\n            ),\n            VectorElement(vector, i) => {\n                let vector_needs_parentheses = vector.precedence() < isize::MAX;\n\n                write!(\n                    f,\n                    \"{}{}{}[{}]\",\n                    if vector_needs_parentheses { \"(\" } else { \"\" },\n                    vector,\n                    if vector_needs_parentheses { \")\" } else { \"\" },\n                    i,\n                )\n            }\n            Matrix(m) => write!(\n                f,\n                \"[{}]\",\n                m.row_iter()\n                    .map(|row| format!(\n                        \"[{}]\",\n                        row.iter()\n                            .map(|element| element.to_string())\n                            .collect::<Vec<_>>()\n                            .join(\", \"),\n                    ))\n                    .collect::<Vec<_>>()\n                    .join(\", \"),\n            ),\n            MatrixElement(matrix, i, j) => {\n                let matrix_needs_parentheses = matrix.precedence() < isize::MAX;\n\n                write!(\n                    f,\n                    \"{}{}{}[{}, {}]\",\n                    if matrix_needs_parentheses { \"(\" } else { \"\" },\n                    matrix,\n                    if matrix_needs_parentheses { \")\" } else { \"\" },\n                    i,\n                    j,\n                )\n            }\n            Boolean(boolean) => write!(f, \"{}\", boolean),\n            Negation(a) => self.fmt_prefix(f, \"-\", a),\n            Not(a) => self.fmt_prefix(f, \"!\", a),\n            Sum(a, b) => self.fmt_infix(f, \"+\", a, b),\n            Difference(a, b) => self.fmt_infix(f, \"-\", a, b),\n            Product(a, b) => self.fmt_infix(f, \"*\", a, b),\n            Quotient(a, b) => self.fmt_infix(f, \"/\", a, b),\n            Remainder(a, b) => self.fmt_infix(f, \"%\", a, b),\n            Power(a, b) => self.fmt_infix(f, \"^\", a, b),\n            Equal(a, b) => self.fmt_infix(f, \"==\", a, b),\n            NotEqual(a, b) => self.fmt_infix(f, \"!=\", a, b),\n            LessThan(a, b) => self.fmt_infix(f, \"<\", a, b),\n            LessThanOrEqual(a, b) => self.fmt_infix(f, \"<=\", a, b),\n            GreaterThan(a, b) => self.fmt_infix(f, \">\", a, b),\n            GreaterThanOrEqual(a, b) => self.fmt_infix(f, \">=\", a, b),\n            And(a, b) => self.fmt_infix(f, \"&&\", a, b),\n            Or(a, b) => self.fmt_infix(f, \"||\", a, b),\n        }\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use nalgebra::{dmatrix, dvector};\n\n    use crate::expression::{Expression, Expression::*};\n    use crate::helpers::*;\n\n    #[track_caller]\n    fn t(expression: Expression, string: &str) {\n        assert_eq!(expression.to_string(), string);\n    }\n\n    #[test]\n    fn variables() {\n        t(var(\"a\"), \"a\");\n        t(var(\"A\"), \"A\");\n        t(var(\"Named_Variable\"), \"Named_Variable\");\n    }\n\n    #[test]\n    fn functions() {\n        t(fun(var(\"f\"), []), \"f()\");\n        t(fun(var(\"f\"), [var(\"a\")]), \"f(a)\");\n        t(fun(var(\"f\"), [var(\"a\"), int(1)]), \"f(a, 1)\");\n        t(\n            fun(\n                var(\"f\"),\n                [fun(var(\"g\"), [var(\"a\")]), fun(var(\"h\"), [var(\"b\")])],\n            ),\n            \"f(g(a), h(b))\",\n        );\n        t(fun(fun(var(\"f\"), [var(\"a\")]), [var(\"b\")]), \"(f(a))(b)\");\n        t(fun(var(\"f\") + var(\"g\"), [var(\"a\")]), \"(f + g)(a)\");\n    }\n\n    #[test]\n    fn integers() {\n        t(int(0), \"0\");\n        t(int(1), \"1\");\n        t(int(-1), \"-1\");\n        t(int(1234567890), \"1234567890\");\n        t(int(-1234567890), \"-1234567890\");\n        t(int(9876543210u64), \"9876543210\");\n        t(int(-9876543210i64), \"-9876543210\");\n    }\n\n    #[test]\n    fn rational_numbers() {\n        t(rat(0, 1), \"0\");\n        t(ratd(0, 1), \"0\");\n        t(rat(0, -1), \"0\");\n        t(ratd(0, -1), \"0\");\n        t(rat(1, 1), \"1\");\n        t(ratd(1, 1), \"1\");\n        t(rat(-1, 1), \"-1\");\n        t(ratd(-1, 1), \"-1\");\n        t(rat(1, 2), \"1/2\");\n        t(ratd(1, 2), \"0.5\");\n        t(rat(3, 2), \"3/2\");\n        t(ratd(3, 2), \"1.5\");\n        t(rat(1, 3), \"1/3\");\n        t(ratd(1, 3), \"1/3\");\n        t(rat(123, 40), \"123/40\");\n        t(ratd(123, 40), \"3.075\");\n        t(rat(123, -40), \"-123/40\");\n        t(ratd(123, -40), \"-3.075\");\n        t(rat(-123, -40), \"123/40\");\n        t(ratd(-123, -40), \"3.075\");\n    }\n\n    #[test]\n    fn complex_numbers() {\n        t(com(0, 1, 0, 1), \"0\");\n        t(comd(0, 1, 0, 1), \"0\");\n        t(com(1, 1, 0, 1), \"1\");\n        t(comd(1, 1, 0, 1), \"1\");\n        t(com(0, 1, 1, 1), \"i\");\n        t(comd(0, 1, 1, 1), \"i\");\n        t(com(-1, 1, 0, 1), \"-1\");\n        t(comd(-1, 1, 0, 1), \"-1\");\n        t(com(0, 1, -1, 1), \"-i\");\n        t(comd(0, 1, -1, 1), \"-i\");\n        t(com(1, 1, 1, 1), \"1 + i\");\n        t(comd(1, 1, 1, 1), \"1 + i\");\n        t(com(1, 1, -1, 1), \"1 - i\");\n        t(comd(1, 1, -1, 1), \"1 - i\");\n        t(com(-1, 1, 1, 1), \"i - 1\");\n        t(comd(-1, 1, 1, 1), \"i - 1\");\n        t(com(-1, 1, -1, 1), \"-1 - i\");\n        t(comd(-1, 1, -1, 1), \"-1 - i\");\n        t(com(123, -40, 1, 3), \"1/3*i - 123/40\");\n        t(comd(123, -40, 1, 3), \"1/3*i - 3.075\");\n        t(com(1, 3, 123, 40), \"1/3 + 123/40*i\");\n        t(comd(1, 3, 123, 40), \"1/3 + 3.075*i\");\n    }\n\n    #[test]\n    fn vectors() {\n        t(Vector(dvector![]), \"[]\");\n        t(Vector(dvector![int(1)]), \"[1]\");\n        t(Vector(dvector![int(1), int(2), int(3)]), \"[1, 2, 3]\");\n        t(\n            Vector(dvector![\n                int(1),\n                fun(var(\"f\"), [var(\"a\"), int(1)]),\n                Vector(dvector![int(1), int(2), int(3)])\n            ]),\n            \"[1, f(a, 1), [1, 2, 3]]\",\n        );\n    }\n\n    #[test]\n    fn matrices() {\n        t(Matrix(dmatrix![]), \"[]\");\n        t(Matrix(dmatrix![int(1)]), \"[[1]]\");\n        t(Matrix(dmatrix![int(1), int(2), int(3)]), \"[[1, 2, 3]]\");\n        t(\n            Matrix(dmatrix![\n                int(1), int(2), int(3);\n                int(4), int(5), int(6)\n            ]),\n            \"[[1, 2, 3], [4, 5, 6]]\",\n        );\n        t(\n            Matrix(dmatrix![\n                fun(var(\"f\"), []), int(2), Vector(dvector![int(1)]);\n                Matrix(dmatrix![int(1)]), comd(123, -40, 1, 3), int(6)\n            ]),\n            \"[[f(), 2, [1]], [[[1]], 1/3*i - 3.075, 6]]\",\n        );\n    }\n\n    #[test]\n    fn booleans() {\n        t(Boolean(true), \"true\");\n        t(Boolean(false), \"false\");\n    }\n\n    #[test]\n    fn operators() {\n        t(-int(1), \"-1\");\n        t(-(-int(1)), \"-(-1)\");\n        t(!var(\"A\"), \"!A\");\n        t(!(!var(\"A\")), \"!(!A)\");\n\n        t((int(1) + int(2)) + int(3), \"1 + 2 + 3\");\n        t((int(1) + int(2)) - int(3), \"1 + 2 - 3\");\n        t((int(1) - int(2)) + int(3), \"1 - 2 + 3\");\n        t((int(1) - int(2)) - int(3), \"1 - 2 - 3\");\n        t(int(1) + (int(2) + int(3)), \"1 + 2 + 3\");\n        t(int(1) + (int(2) - int(3)), \"1 + 2 - 3\");\n        t(int(1) - (int(2) + int(3)), \"1 - (2 + 3)\");\n        t(int(1) - (int(2) - int(3)), \"1 - (2 - 3)\");\n\n        t((int(1) * int(2)) * int(3), \"1 * 2 * 3\");\n        t((int(1) * int(2)) / int(3), \"1 * 2 / 3\");\n        t((int(1) / int(2)) * int(3), \"1 / 2 * 3\");\n        t((int(1) / int(2)) / int(3), \"1 / 2 / 3\");\n        t(int(1) * (int(2) * int(3)), \"1 * 2 * 3\");\n        t(int(1) * (int(2) / int(3)), \"1 * 2 / 3\");\n        t(int(1) / (int(2) * int(3)), \"1 / (2 * 3)\");\n        t(int(1) / (int(2) / int(3)), \"1 / (2 / 3)\");\n\n        t((int(1) + int(2)) / int(3), \"(1 + 2) / 3\");\n        t((int(1) / int(2)) + int(3), \"1 / 2 + 3\");\n        t(int(1) + (int(2) / int(3)), \"1 + 2 / 3\");\n        t(int(1) / (int(2) + int(3)), \"1 / (2 + 3)\");\n\n        t(pow(int(1) * int(2), int(3)), \"(1 * 2) ^ 3\");\n        t(pow(int(1), int(2)) * int(3), \"1 ^ 2 * 3\");\n        t(int(1) * pow(int(2), int(3)), \"1 * 2 ^ 3\");\n        t(pow(int(1), int(2) * int(3)), \"1 ^ (2 * 3)\");\n\n        t(pow(pow(int(1), int(2)), int(3)), \"(1 ^ 2) ^ 3\");\n        t(pow(int(1), pow(int(2), int(3))), \"1 ^ 2 ^ 3\");\n\n        t(pow(int(1), int(2)), \"1 ^ 2\");\n        t(pow(int(-1), int(2)), \"(-1) ^ 2\");\n        t(pow(rat(1, 2), int(3)), \"(1/2) ^ 3\");\n        t(pow(ratd(1, 2), int(3)), \"0.5 ^ 3\");\n        t(pow(com(0, 1, -1, 1), int(2)), \"(-i) ^ 2\");\n        t(com(1, 1, 1, 1) * int(2), \"(1 + i) * 2\");\n        t(com(1, 1, -1, 1) - int(2), \"1 - i - 2\");\n        t(int(2) - com(1, 1, -1, 1), \"2 - (1 - i)\");\n\n        // TODO: Comparison operators!\n\n        t(and(and(var(\"A\"), var(\"B\")), var(\"C\")), \"A && B && C\");\n        t(or(and(var(\"A\"), var(\"B\")), var(\"C\")), \"A && B || C\");\n        t(and(or(var(\"A\"), var(\"B\")), var(\"C\")), \"(A || B) && C\");\n        t(or(or(var(\"A\"), var(\"B\")), var(\"C\")), \"A || B || C\");\n        t(and(var(\"A\"), and(var(\"B\"), var(\"C\"))), \"A && B && C\");\n        t(and(var(\"A\"), or(var(\"B\"), var(\"C\"))), \"A && (B || C)\");\n        t(or(var(\"A\"), and(var(\"B\"), var(\"C\"))), \"A || B && C\");\n        t(or(var(\"A\"), or(var(\"B\"), var(\"C\"))), \"A || B || C\");\n    }\n}\n"
  },
  {
    "path": "savage_core/src/simplify.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse crate::{expression::Expression, helpers::*};\n\nimpl Expression {\n    /// Applies standard algebraic simplification rules to the expression,\n    /// and returns the result.\n    ///\n    /// Note that this function does not itself recurse into sub-expressions;\n    /// but since it is called from `evaluate_step`, which *does* recurse,\n    /// simplifications are applied to the entire expression tree during evaluation.\n    pub(crate) fn simplify(&self) -> Self {\n        use crate::expression::Expression::*;\n\n        match self {\n            Negation(a) => {\n                if let Negation(a) = &**a {\n                    *a.clone()\n                } else {\n                    self.clone()\n                }\n            }\n            Not(a) => {\n                if let Not(a) = &**a {\n                    *a.clone()\n                } else {\n                    self.clone()\n                }\n            }\n            Sum(a, b) => {\n                let a = *a.clone();\n                let b = *b.clone();\n\n                if a == int(0) {\n                    b\n                } else if b == int(0) {\n                    a\n                } else if a == b {\n                    int(2) * a\n                } else if a == -b.clone() || b == -a {\n                    int(0)\n                } else {\n                    self.clone()\n                }\n            }\n            Difference(a, b) => {\n                let a = *a.clone();\n                let b = *b.clone();\n\n                if a == int(0) {\n                    -b\n                } else if b == int(0) {\n                    a\n                } else if a == b {\n                    int(0)\n                } else if a == -b.clone() || b == -a.clone() {\n                    int(2) * a\n                } else {\n                    self.clone()\n                }\n            }\n            Product(a, b) => {\n                let a = *a.clone();\n                let b = *b.clone();\n\n                if a == int(1) {\n                    b\n                } else if b == int(1) {\n                    a\n                } else if a == int(0) || b == int(0) {\n                    int(0)\n                } else if a == b {\n                    pow(a, int(2))\n                } else if a == int(1) / b.clone() || b == int(1) / a {\n                    int(1)\n                } else {\n                    self.clone()\n                }\n            }\n            Quotient(a, b) => {\n                let a = *a.clone();\n                let b = *b.clone();\n\n                if b == int(1) {\n                    a\n                } else if a == int(0) {\n                    // FIXME: This is incorrect if `b` evaluates to zero!\n                    int(0)\n                } else if a == b {\n                    // FIXME: This is incorrect if `b` evaluates to zero!\n                    int(1)\n                } else {\n                    self.clone()\n                }\n            }\n            Remainder(a, b) => {\n                let a = *a.clone();\n                let b = *b.clone();\n\n                if a == int(0) || a == b {\n                    // FIXME: This is incorrect if `b` evaluates to zero!\n                    int(0)\n                } else {\n                    self.clone()\n                }\n            }\n            Power(a, b) => {\n                let a = *a.clone();\n                let b = *b.clone();\n\n                if a == int(1) {\n                    int(1)\n                } else if b == int(1) {\n                    a\n                } else if a == int(0) {\n                    // FIXME: This is incorrect if `b` evaluates to zero!\n                    int(0)\n                } else if b == int(0) {\n                    // FIXME: This is incorrect if `a` evaluates to zero!\n                    int(1)\n                } else {\n                    self.clone()\n                }\n            }\n            Equal(a, b) | LessThanOrEqual(a, b) | GreaterThanOrEqual(a, b) => {\n                if a == b {\n                    Boolean(true)\n                } else {\n                    self.clone()\n                }\n            }\n            NotEqual(a, b) | LessThan(a, b) | GreaterThan(a, b) => {\n                if a == b {\n                    Boolean(false)\n                } else {\n                    self.clone()\n                }\n            }\n            And(a, b) => {\n                let a = *a.clone();\n                let b = *b.clone();\n\n                if a == Boolean(true) {\n                    b\n                } else if b == Boolean(true) {\n                    a\n                } else if a == Boolean(false) || b == Boolean(false) {\n                    Boolean(false)\n                } else if a == b {\n                    a\n                } else if a == !b.clone() || b == !a {\n                    Boolean(false)\n                } else {\n                    self.clone()\n                }\n            }\n            Or(a, b) => {\n                let a = *a.clone();\n                let b = *b.clone();\n\n                if a == Boolean(false) {\n                    b\n                } else if b == Boolean(false) {\n                    a\n                } else if a == Boolean(true) || b == Boolean(true) {\n                    Boolean(true)\n                } else if a == b {\n                    a\n                } else if a == !b.clone() || b == !a {\n                    Boolean(true)\n                } else {\n                    self.clone()\n                }\n            }\n            _ => self.clone(),\n        }\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use crate::expression::Expression;\n\n    #[track_caller]\n    fn t(expression: &str, result: &str) {\n        assert_eq!(\n            expression\n                .parse::<Expression>()\n                .unwrap()\n                .simplify()\n                .to_string(),\n            result,\n        );\n    }\n\n    #[test]\n    fn arithmetic() {\n        t(\"-(-a)\", \"a\");\n\n        t(\"0 + a\", \"a\");\n        t(\"a + 0\", \"a\");\n        t(\"a + a\", \"2 * a\");\n        t(\"(-a) + a\", \"0\");\n        t(\"a + (-a)\", \"0\");\n\n        t(\"0 - a\", \"-a\");\n        t(\"a - 0\", \"a\");\n        t(\"a - a\", \"0\");\n        t(\"(-a) - a\", \"2 * -a\");\n        t(\"a - (-a)\", \"2 * a\");\n\n        t(\"1 * a\", \"a\");\n        t(\"a * 1\", \"a\");\n        t(\"0 * a\", \"0\");\n        t(\"a * 0\", \"0\");\n        t(\"a * a\", \"a ^ 2\");\n        t(\"(1 / a) * a\", \"1\");\n        t(\"a * (1 / a)\", \"1\");\n\n        t(\"a / 1\", \"a\");\n        t(\"0 / a\", \"0\");\n        t(\"a / a\", \"1\");\n\n        t(\"0 % a\", \"0\");\n        t(\"a % a\", \"0\");\n\n        t(\"1 ^ a\", \"1\");\n        t(\"a ^ 1\", \"a\");\n        t(\"0 ^ a\", \"0\");\n        t(\"a ^ 0\", \"1\");\n    }\n\n    #[test]\n    fn logic() {\n        t(\"!(!a)\", \"a\");\n\n        t(\"true && a\", \"a\");\n        t(\"a && true\", \"a\");\n        t(\"false && a\", \"false\");\n        t(\"a && false\", \"false\");\n        t(\"a && a\", \"a\");\n        t(\"(!a) && a\", \"false\");\n        t(\"a && (!a)\", \"false\");\n\n        t(\"false || a\", \"a\");\n        t(\"a || false\", \"a\");\n        t(\"true || a\", \"true\");\n        t(\"a || true\", \"true\");\n        t(\"a || a\", \"a\");\n        t(\"(!a) || a\", \"true\");\n        t(\"a || (!a)\", \"true\");\n    }\n\n    #[test]\n    fn comparisons() {\n        t(\"a == a\", \"true\");\n        t(\"a != a\", \"false\");\n        t(\"a < a\", \"false\");\n        t(\"a <= a\", \"true\");\n        t(\"a > a\", \"false\");\n        t(\"a >= a\", \"true\");\n    }\n}\n"
  },
  {
    "path": "savage_macros/Cargo.toml",
    "content": "[package]\nname = \"savage_macros\"\nversion = \"0.1.0\"\nauthors = [\"Philipp Emanuel Weidmann <pew@worldwidemann.com>\"]\ndescription = \"A primitive computer algebra system (macro helper crate, NOT INTENDED FOR USE BY THIRD-PARTY CRATES)\"\nrepository = \"https://github.com/p-e-w/savage\"\nreadme = \"README.md\"\nlicense = \"AGPL-3.0-or-later\"\nedition = \"2021\"\n\n[lib]\nproc-macro = true\n\n[dependencies]\nsyn = \"1.0.85\"\nquote = \"1.0.14\"\ndarling = \"0.14.1\"\n"
  },
  {
    "path": "savage_macros/src/lib.rs",
    "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>\n\nuse darling::FromMeta;\nuse proc_macro::TokenStream;\nuse quote::{format_ident, quote};\nuse syn::{\n    parse_macro_input, punctuated::Punctuated, token::Comma, AttributeArgs, ExprArray, FnArg,\n    ItemFn, Path, Type,\n};\n\n#[derive(FromMeta)]\nstruct Arguments {\n    name: String,\n    description: String,\n    examples: ExprArray,\n    categories: ExprArray,\n}\n\n/// Generates code required for the marked function to be usable in a function expression.\n/// Function metadata is generated from the provided attribute arguments.\n#[proc_macro_attribute]\npub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {\n    let arguments = match Arguments::from_list(&parse_macro_input!(attr as AttributeArgs)) {\n        Ok(arguments) => arguments,\n        Err(error) => return TokenStream::from(error.write_errors()),\n    };\n\n    let name_argument = arguments.name;\n    let description_argument = arguments.description;\n    let examples_argument = arguments.examples;\n    let categories_argument = arguments.categories;\n\n    let item_fn = parse_macro_input!(item as ItemFn);\n\n    let name = &item_fn.sig.ident;\n    let metadata_name = format_ident!(\"{}_METADATA\", name.to_string().to_uppercase());\n    let proxy_name = format_ident!(\"{}_proxy\", name);\n\n    let parameters = item_fn.sig.inputs.iter().map(|fn_arg| {\n        if let FnArg::Typed(pat_type) = fn_arg {\n            if let Type::Path(type_path) = &*pat_type.ty {\n                match type_path.path.get_ident().unwrap().to_string().as_str() {\n                    \"Expression\" => quote! { crate::functions::Parameter::Expression },\n                    \"Integer\" => quote! { crate::functions::Parameter::Integer },\n                    \"NonNegativeInteger\" => {\n                        quote! { crate::functions::Parameter::NonNegativeInteger }\n                    }\n                    \"PositiveInteger\" => {\n                        quote! { crate::functions::Parameter::PositiveInteger }\n                    }\n                    \"Rational\" => quote! { crate::functions::Parameter::Rational },\n                    \"Complex\" => quote! { crate::functions::Parameter::Complex },\n                    \"Vector\" => quote! { crate::functions::Parameter::Vector },\n                    \"Matrix\" => quote! { crate::functions::Parameter::Matrix },\n                    \"SquareMatrix\" => quote! { crate::functions::Parameter::SquareMatrix },\n                    \"bool\" => quote! { crate::functions::Parameter::Boolean },\n                    _ => unimplemented!(),\n                }\n            } else {\n                unreachable!();\n            }\n        } else {\n            unreachable!();\n        }\n    });\n\n    let arguments =\n        (0..item_fn.sig.inputs.len()).map(|i| quote! { arguments[#i].clone().try_into()? });\n\n    let tokens = quote! {\n        #item_fn\n\n        pub(crate) const #metadata_name: crate::functions::Metadata = crate::functions::Metadata {\n            name: #name_argument,\n            description: #description_argument,\n            parameters: &[#(#parameters),*],\n            examples: &#examples_argument,\n            categories: &#categories_argument,\n        };\n\n        pub(crate) fn #proxy_name(arguments: &[crate::expression::Expression]) ->\n            ::std::result::Result<crate::expression::Expression, crate::expression::Expression> {\n            ::std::result::Result::Ok(#name(#(#arguments),*).into())\n        }\n    };\n\n    tokens.into()\n}\n\n/// Returns a vector of function definitions generated from the base function paths provided as arguments.\n#[proc_macro]\npub fn functions(input: TokenStream) -> TokenStream {\n    let mut statements = Vec::new();\n\n    for path in parse_macro_input!(input with Punctuated::<Path, Comma>::parse_terminated) {\n        let name = &path.segments.last().unwrap().ident;\n\n        let mut metadata_path = path.clone();\n        metadata_path.segments.last_mut().unwrap().ident =\n            format_ident!(\"{}_METADATA\", name.to_string().to_uppercase());\n\n        let mut proxy_path = path.clone();\n        proxy_path.segments.last_mut().unwrap().ident = format_ident!(\"{}_proxy\", name);\n\n        statements.push(quote! {\n            functions.push(Function {\n                metadata: #metadata_path,\n                implementation: wrap_proxy(#metadata_path.parameters, #proxy_path),\n            });\n        });\n    }\n\n    let tokens = quote! {{\n        let mut functions = Vec::new();\n\n        #(#statements)*\n\n        functions\n    }};\n\n    tokens.into()\n}\n"
  }
]