Full Code of p-e-w/savage for AI

master 24e25a6a5add cached
29 files
179.6 KB
42.8k tokens
156 symbols
1 requests
Download .txt
Repository: p-e-w/savage
Branch: master
Commit: 24e25a6a5add
Files: 29
Total size: 179.6 KB

Directory structure:
gitextract_86suw3hs/

├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       └── continuous_integration.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE
├── README.md
├── savage/
│   ├── Cargo.toml
│   ├── help/
│   │   ├── footer.md
│   │   └── header.md
│   └── src/
│       ├── command.rs
│       ├── help.rs
│       ├── input.rs
│       └── main.rs
├── savage_core/
│   ├── Cargo.toml
│   └── src/
│       ├── evaluate.rs
│       ├── expression.rs
│       ├── functions/
│       │   ├── combinatorics.rs
│       │   ├── linear_algebra.rs
│       │   ├── logic.rs
│       │   ├── mod.rs
│       │   └── number_theory.rs
│       ├── helpers.rs
│       ├── lib.rs
│       ├── parse.rs
│       ├── print.rs
│       └── simplify.rs
└── savage_macros/
    ├── Cargo.toml
    └── src/
        └── lib.rs

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/dependabot.yml
================================================
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2

updates:
  - package-ecosystem: "cargo"
    directory: "/"
    schedule:
      interval: "weekly"


================================================
FILE: .github/workflows/continuous_integration.yml
================================================
# Based on https://github.com/actions-rs/meta/blob/master/recipes/msrv.md

on: [push, pull_request]

name: Continuous integration

jobs:
  check:
    name: Check
    runs-on: ubuntu-latest
    strategy:
      matrix:
        rust:
          - stable
          - 1.56.0
    steps:
      - uses: actions/checkout@v2
      - uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: ${{ matrix.rust }}
          override: true
      - uses: actions-rs/cargo@v1
        with:
          command: check

  test:
    name: Test Suite
    runs-on: ubuntu-latest
    strategy:
      matrix:
        rust:
          - stable
          - 1.56.0
    steps:
      - uses: actions/checkout@v2
      - uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: ${{ matrix.rust }}
          override: true
      - uses: actions-rs/cargo@v1
        with:
          command: test

  fmt:
    name: Rustfmt
    runs-on: ubuntu-latest
    strategy:
      matrix:
        rust:
          - stable
    steps:
      - uses: actions/checkout@v2
      - uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: ${{ matrix.rust }}
          override: true
      - run: rustup component add rustfmt
      - uses: actions-rs/cargo@v1
        with:
          command: fmt
          args: --all -- --check

  clippy:
    name: Clippy
    runs-on: ubuntu-latest
    strategy:
      matrix:
        rust:
          - stable
    steps:
      - uses: actions/checkout@v2
      - uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: ${{ matrix.rust }}
          override: true
      - run: rustup component add clippy
      - uses: actions-rs/cargo@v1
        with:
          command: clippy
          args: -- -D warnings


================================================
FILE: .gitignore
================================================
/target


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).


## [Unreleased]

### Added

#### REPL

- Basic help system
- Ability to define custom variables and functions
- Proper formatting for parse errors

### Changed

### Fixed


## [0.2.0] - 2022-03-13

### Added

#### Core

- Basic support for vectors and matrices
- Algebraic simplification during evaluation
- Infrastructure for evaluating functions
- Macro-based function dispatch system
- New built-in functions:
  - `and`
  - `det`
  - `factorial`
  - `is_prime`
  - `nth_prime`
  - `prime_pi`

#### REPL

- Persistent input history
- Multi-line editing mode
- Syntax highlighting for input and output
- Highlighting of matching brackets in input

### Fixed

#### Core

- Type inflation in parser
- Exponential blowup in parser

#### REPL

- Error on empty input


## [0.1.0] - 2021-11-28

Initial release with basic REPL and support for elementary arithmetic and logic.


[unreleased]: https://github.com/p-e-w/savage/compare/v0.2.0...HEAD
[0.2.0]: https://github.com/p-e-w/savage/compare/v0.1.0...v0.2.0
[0.1.0]: https://github.com/p-e-w/savage/releases/tag/v0.1.0


================================================
FILE: Cargo.toml
================================================
[workspace]
members = [
    "savage_macros",
    "savage_core",
    "savage",
]

[profile.release]
codegen-units = 1
opt-level = 3
lto = true
#strip = true


================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================
# Savage Computer Algebra System

Savage is a new computer algebra system written from scratch in pure Rust.
Its goals are correctness, simplicity, and usability, in that order.
The entire system compiles to a single, dependency-free executable just
2.5 MB in size. While that executable will of course grow as Savage matures,
the plan is to eventually deliver a useful computer algebra system in 5 MB
or less.

![Screenshot](https://user-images.githubusercontent.com/2702526/158006796-7d3aad2a-217f-421a-b3f8-20498d32b0f0.png)

The name "Savage" is a reference/homage to [Sage](https://www.sagemath.org/),
the leading open-source computer algebra system. Since Sage already exists
and works very well, it would make no sense to attempt to create a clone of it.
Instead, Savage aims to be something of an antithesis to Sage: Where Sage is
a unified frontend to dozens of mathematics packages, Savage is a tightly-integrated,
monolithic system. Where Sage covers many areas of mathematics, including cutting-edge
research topics, Savage will focus on the "bread and butter" math employed by
engineers and other people who *use*, rather than develop, mathematical concepts.
Where Sage features amazingly sophisticated implementations of countless functions,
Savage has code that is savagely primitive, getting the job done naively but correctly,
without worrying whether the performance is still optimal when the input is
a million-digit number.

**Savage is in early development and is not yet ready to be used for serious work.**
It is, however, ready to play around with, and is happily accepting contributions
to move the project forward.


## Features

This is what Savage offers **today:**

* Arbitrary-precision integer, rational, and complex arithmetic
* Input, simplification, and evaluation of symbolic expressions
* First-class support for vectors and matrices, with coefficients being arbitrary expressions
* REPL with syntax and bracket highlighting, persistent history, and automatic multi-line input
* Macro-based system for defining functions with metadata and automatic type checking
* [Usable as a library](#savage-as-a-library) from any Rust program

The following features are **planned,** with some of the groundwork already done:

* User-defined variables and functions
* Built-in help system
* Many more functions from various areas of math
* More powerful expression simplification
* Jupyter kernel

By contrast, the following are considered **non-features** for Savage,
and there are no plans to add them either now or in the future:

* *Advanced/research-level mathematics:* As a rule of thumb, if it doesn't belong
  in a typical undergraduate course, it probably doesn't belong in Savage.
* *Physics/finance/machine learning/other areas adjacent to math:* The scope would
  grow without bounds and that is exactly what Savage aims to avoid.
* *Formal verification of implementations:* The required technologies aren't mature yet
  and Savage is not a research project.
* *Performance at the expense of simplicity:* Yes, I know that multiplication
  can be done faster using some fancy Fourier tricks. No, I won't implement that.
* *General-purpose programming:* Too complex, and not the focus of this project.
* *File/network I/O:* Savage performs computations, nothing more and nothing less.
  Functions have no side effects.
* *Modules/packages/extensions/plugins:* The world is complicated enough.
  Either something is built in, or Savage doesn't have it at all.
* *GUI:* Although it's possible to create a GUI frontend backed by the `savage_core`
  crate, there are no plans to do so within the Savage project itself.


## Installation

Building Savage from source requires [Rust](https://www.rust-lang.org/) **1.56 or later.**
Once a supported version of Rust is installed on your system, you only need to run

```
cargo install savage
```

to install the Savage REPL to your Cargo binary directory (usually `$HOME/.cargo/bin`).
Of course, you can also just clone this repository and `cargo run` the REPL from the
repository root.

In the future, there will be pre-built executables for major platforms
available with every Savage release.


## Tour

### Arithmetic

Arithmetic operations in Savage have no precision limits (other than the amount
of memory available in your system):

```
in: 1 + 1
out: 2

in: 1.1 ^ 100
out: 13780.612339822270184118337172089636776264331200038466433146477552154985209
5523076769401159497458526446001

in: 3 ^ 4 ^ 5
out: 373391848741020043532959754184866588225409776783734007750636931722079040617
26525122999368893880397722046876506543147515810872705459216085858135133698280918
73141917485942625809388070199519564042855718180410466812887974029255176680123406
17298396574731619152386723046235125934896058590588284654793540505936202376547807
44273058214452705898875625145281779341335214192074462302751872918543286237573706
39854853194764169262638199728870069070138992565242971985276987492741962768110607
02333710356481
```

Results are automatically printed in either fractional or decimal form,
depending on whether the input contained fractions or decimal numbers:

```
in: 6/5 * 3
out: 18/5

in: 1.2 * 3
out: 3.6
```

The variable `i` is predefined to represent the imaginary unit, allowing for
complex numbers to be entered using standard notation:

```
in: (1 + i) ^ 12
out: -64
```

### Linear algebra

Vectors and matrices are first-class citizens in Savage and support the standard
addition, subtraction, multiplication, and exponentiation operators. Coefficients
can be arbitrary expressions:

```
in: [a, b] - [a, c]
out: [0, b - c]

in: [a, b, c] * 3
out: [a * 3, b * 3, c * 3]

in: [[1, 2], [3, 4]] * [5, 6]
out: [17, 39]
```

Determinants are evaluated symbolically:

```
in: det([[a, 2], [3, a]])
out: a ^ 2 - 6
```

### Logic

The standard `&&`, `||`, `!`, and comparison operators are available. Savage
automatically evaluates many tautologies and contradictions, even in the presence
of undefined variables:

```
in: a && true
out: a

in: a || true
out: true

in: a || !a
out: true

in: a < a
out: false
```

### Number theory

Verify that the Mersenne number *M<sub>31</sub>* is a prime number:

```
in: is_prime(2^31 - 1)
out: true
```

Compute the ten millionth prime number:

```
in: nth_prime(10^7)
out: 179424673
```

Compute the number of primes up to ten million:

```
in: prime_pi(10^7)
out: 664579
```

These functions for dealing with prime numbers are powered by the ultra-fast
[`primal`](https://crates.io/crates/primal) crate. Many more functions from
number theory will be added to Savage in the future.


## Savage as a library

All of Savage's actual computer algebra functionality is contained in the
[`savage_core`](https://crates.io/crates/savage_core) crate. That crate exposes
everything necessary to build software that leverages symbolic math capabilities.
Assuming `savage_core` has been added as a dependency to a crate's `Cargo.toml`,
it can be used like this:

```rust
use std::collections::HashMap;

use savage_core::{expression::Expression, helpers::*};

fn main() {
    // Expressions can be constructed by parsing a string literal...
    let lhs = "det([[a, 2], [3, a]])".parse::<Expression>().unwrap();
    // ... or directly from code using helper functions.
    let rhs = pow(var("a"), int(2)) - int(6);

    let mut context = HashMap::new();
    // The context can be used to set the values of variables during evaluation.
    // Change "b" to "a" to see this in action!
    context.insert("b".to_owned(), int(3));

    assert_eq!(lhs.evaluate(context), Ok(rhs));
}
```

Please note that at this point, the primary purpose of the `savage_core` crate is
to power the Savage REPL, so any use by third-party crates should be considered
somewhat experimental. Note also that like the rest of Savage, `savage_core` is
licensed under the terms of the [AGPL](LICENSE), which imposes conditions on any
dependent software that go beyond what is required by the more common permissive
licenses. Make sure you understand the AGPL and its implications before adding
`savage_core` as a dependency to your crate.


## Acknowledgments

Savage stands on the shoulders of the giant that is the Rust ecosystem. Among the
many third-party crates that Savage relies on, I want to highlight two that play
a particularly important role:

* [`num`](https://crates.io/crates/num) is the fundamental crate for all numeric
  computations in Savage. It provides the crucial `BigInt` type that enables
  standard arithmetic operations to be performed with arbitrary precision.
  `num`'s code is of high quality and extremely well tested.
* [`chumsky`](https://crates.io/crates/chumsky) is the magic behind Savage's expression
  parser. I have looked at every parser crate currently available and found Chumsky's
  API to be by far the most intuitive. Furthermore, Chumsky's author is highly
  responsive on the issue tracker, and has personally helped me understand and resolve
  two major issues that arose during the development of Savage's parser.


## License

Copyright &copy; 2021-2022  Philipp Emanuel Weidmann (<pew@worldwidemann.com>)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

**By contributing to this project, you agree to release your
contributions under the same license.**


================================================
FILE: savage/Cargo.toml
================================================
[package]
name = "savage"
version = "0.2.0"
authors = ["Philipp Emanuel Weidmann <pew@worldwidemann.com>"]
description = "A primitive computer algebra system (REPL)"
repository = "https://github.com/p-e-w/savage"
readme = "README.md"
license = "AGPL-3.0-or-later"
edition = "2021"

[dependencies]
lazy_static = "1.4.0"
directories = "4.0.1"
crossterm = "0.25.0"
ansi_term = "0.12.1"
rustyline = "9.0.0"
rustyline-derive = "0.7.0"
termimad = "0.20.2"
regex = "1.6.0"
chumsky = "0.8.0"
ariadne = "0.1.5"
savage_core = { path = "../savage_core", version = "0.2.0" }


================================================
FILE: savage/help/footer.md
================================================
## License

Copyright (C) 2021-2022  Philipp Emanuel Weidmann (**pew@worldwidemann.com**)

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see **https://www.gnu.org/licenses/**.


================================================
FILE: savage/help/header.md
================================================
# Savage Computer Algebra System

Savage is a new computer algebra system written from scratch in pure Rust. Its goals are correctness, simplicity, and usability, in that order.

This 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.

For 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.


## Basic usage

Type mathematical expressions in the REPL using standard notation and press *Enter* to evaluate them:

```
in: 1 + 1
out: 2
```

Savage 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:

```
in: 6/5 * 3
out: 18/5

in: 1.2 * 3
out: 3.6

in: (1 + i) ^ 12
out: -64
```

It 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:

```
in: a && true
out: a

in: a || true
out: true

in: a || !a
out: true

in: a < a
out: false
```


## Vectors and matrices

A 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.

Vectors and matrices support the standard arithmetic operations:

```
in: [a, b] - [a, c]
out: [0, b - c]

in: [a, b, c] * 3
out: [a * 3, b * 3, c * 3]

in: [[1, 2], [3, 4]] * [5, 6]
out: [17, 39]
```

Individual elements of vectors and matrices can be accessed using the index notation familiar from many programming languages:

```
in: v = [1, 2, 3]
in: v[1]
out: 2

in: m = [[1, 2], [3, 4]]
in: m[1, 0]
out: 3
```


## Variables and functions

Symbolic 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:

```
in: a = 1
in: b = 2
in: a + b
out: 3
```

Functions can also be defined with a syntax that is essentially identical to that used in standard mathematical notation:

```
in: sum(x, y) = x + y
in: sum(1, 2)
out: 3
```


## Built-in functions

The following named functions are available in the REPL without needing to be explicitly loaded or manually defined:


================================================
FILE: savage/src/command.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use std::str::FromStr;

use chumsky::prelude::*;
use savage_core::{
    expression::Expression,
    parse::{parser as expression, Error},
};

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Command {
    EvaluateExpression(Expression),
    DefineVariable(String, Expression),
    DefineFunction(String, Vec<String>, Expression),
    ShowHelp(Option<String>),
}

fn parser() -> impl Parser<char, Command, Error = Error> {
    text::ident()
        .padded()
        .then_ignore(just('='))
        .then(expression())
        .map(|(identifier, expression)| Command::DefineVariable(identifier, expression))
        .or(text::ident()
            .padded()
            .then(
                text::ident()
                    .padded()
                    .separated_by(just(','))
                    .padded()
                    .delimited_by(just('('), just(')'))
                    .padded(),
            )
            .then_ignore(just('='))
            .then(expression())
            .map(|((identifier, argument_identifiers), expression)| {
                Command::DefineFunction(identifier, argument_identifiers, expression)
            }))
        .or(expression().map(Command::EvaluateExpression))
        .or(just('?')
            .padded()
            .ignore_then(text::ident().padded().or_not())
            .map(Command::ShowHelp))
}

impl FromStr for Command {
    type Err = Vec<Error>;

    fn from_str(string: &str) -> Result<Self, Self::Err> {
        parser().then_ignore(end()).parse(string)
    }
}

#[cfg(test)]
mod tests {
    use savage_core::helpers::*;

    use crate::command::{Command, Command::*};

    #[track_caller]
    fn t(string: &str, command: Command) {
        assert_eq!(string.parse(), Ok(command));
    }

    #[test]
    fn parse() {
        t("   a ", EvaluateExpression(var("a")));
        t("a ==b ", EvaluateExpression(eq(var("a"), var("b"))));

        t(" a=1", DefineVariable("a".to_owned(), int(1)));
        t(
            "a   =b==  c",
            DefineVariable("a".to_owned(), eq(var("b"), var("c"))),
        );

        t("f(  )= 1", DefineFunction("f".to_owned(), vec![], int(1)));
        t(
            " f (x) =x ^ 2",
            DefineFunction("f".to_owned(), vec!["x".to_owned()], pow(var("x"), int(2))),
        );
        t(
            "f( x )=( (x)== (y))  ",
            DefineFunction("f".to_owned(), vec!["x".to_owned()], eq(var("x"), var("y"))),
        );
        t(
            "f( x ,y)= g(x, y)",
            DefineFunction(
                "f".to_owned(),
                vec!["x".to_owned(), "y".to_owned()],
                fun(var("g"), [var("x"), var("y")]),
            ),
        );

        t(" ?  ", ShowHelp(None));
        t("?is_prime  ", ShowHelp(Some("is_prime".to_owned())));
        t("?  is_prime", ShowHelp(Some("is_prime".to_owned())));
    }
}


================================================
FILE: savage/src/help.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use std::{
    collections::HashMap,
    io::{stdout, Write},
};

use crossterm::{
    cursor,
    event::{self, Event, KeyEvent},
    queue,
    style::Stylize,
    terminal::{
        self, ClearType, DisableLineWrap, EnableLineWrap, EnterAlternateScreen,
        LeaveAlternateScreen,
    },
};
use lazy_static::lazy_static;
use savage_core::functions::functions;
use termimad::{Area, Error, MadSkin, MadView};

const HELP_HEADER: &str = include_str!("../help/header.md");
const HELP_FOOTER: &str = include_str!("../help/footer.md");

lazy_static! {
    pub static ref FUNCTION_HELP_TEXTS: HashMap<String, String> = {
        let mut texts = HashMap::new();

        for function in functions() {
            let metadata = function.metadata;

            let text = format!(
                "**{}** - {}\n\n*Syntax:*\n```\n{}({})\n```\n\n*Examples:*\n```\n{}\n```\n\n*Categories:*\n{}\n",
                metadata.name,
                metadata.description,
                metadata.name,
                metadata
                    .parameters
                    .iter()
                    .map(|p| format!("{:?}", p))
                    .collect::<Vec<_>>()
                    .join(", "),
                metadata
                    .examples
                    .iter()
                    .map(|(i, o)| format!("in: {}\nout: {}", i, o))
                    .collect::<Vec<_>>()
                    .join("\n\n"),
                metadata.categories.join(", "),
            );

            texts.insert(metadata.name.to_owned(), text);
        }

        texts
    };
    pub static ref HELP_TEXT: String = {
        let mut text = String::from(HELP_HEADER);

        text.push_str("\n---\n\n");

        for function in functions() {
            text.push_str(&FUNCTION_HELP_TEXTS[function.metadata.name]);
            text.push_str("\n---\n\n");
        }

        text.push('\n');
        text.push_str(HELP_FOOTER);
        text.push('\n');

        text
    };
}

fn view_area() -> Area {
    let mut area = Area::full_screen();

    area.pad_for_max_width(120);

    // Make space for bottom bar.
    area.height -= 1;

    area
}

pub fn show_help(text: String) -> Result<(), Error> {
    // Based on https://github.com/Canop/termimad/blob/5ab13e600f05c0217e270181dd5d9288210f893f/examples/scrollable/main.rs
    use crossterm::event::KeyCode::*;

    let mut stdout = stdout();

    queue!(stdout, EnterAlternateScreen, DisableLineWrap, cursor::Hide)?;
    terminal::enable_raw_mode()?;

    let mut view = MadView::from(text, view_area(), MadSkin::default());

    loop {
        view.write_on(&mut stdout)?;

        print!(
            "\n\r{}{}{}{}{}{}{}{}",
            "Press ".reverse(),
            "\u{2191}".bold().reverse(),
            " and ".reverse(),
            "\u{2193}".bold().reverse(),
            " to scroll, ".reverse(),
            "Q".bold().reverse(),
            " to quit".reverse(),
            " ".repeat(view_area().width as usize).reverse(),
        );

        stdout.flush()?;

        match event::read() {
            Ok(Event::Key(KeyEvent { code, .. })) => match code {
                Up | Char('k') => view.try_scroll_lines(-1),
                Down | Char('j') | Enter => view.try_scroll_lines(1),
                PageUp => view.try_scroll_pages(-1),
                PageDown | Char(' ') => view.try_scroll_pages(1),
                Char('q') | Esc => break,
                _ => {}
            },
            Ok(Event::Resize(..)) => {
                queue!(stdout, terminal::Clear(ClearType::All))?;
                view.resize(&view_area());
            }
            _ => {}
        }
    }

    terminal::disable_raw_mode()?;
    queue!(stdout, cursor::Show, EnableLineWrap, LeaveAlternateScreen)?;
    stdout.flush()?;

    Ok(())
}


================================================
FILE: savage/src/input.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use std::borrow::Cow;

use ansi_term::Style;
use lazy_static::lazy_static;
use regex::Regex;
use rustyline::{
    highlight::Highlighter,
    validate::{ValidationContext, ValidationResult, Validator},
    Result,
};
use rustyline_derive::{Completer, Helper, Hinter};
use savage_core::{expression::Expression, parse::ErrorReason};

enum TokenType {
    Literal,
    Variable,
    Operator,
    Bracket,
    Separator,
    Whitespace,
    Invalid,
}

fn tokenize(input: &str) -> Vec<(String, TokenType)> {
    use TokenType::*;

    lazy_static! {
        static ref REGEX: Regex = Regex::new(
            &[
                r"(?P<literal>[0-9]+(?:\.[0-9]+)?|true|false)",
                r"(?P<variable>[a-zA-Z_][a-zA-Z0-9_]*)",
                r"(?P<operator>[+\-*/%^!=<>&|]+)",
                r"(?P<bracket>[()\[\]])",
                r"(?P<separator>,)",
                r"(?P<whitespace>\s+)",
            ]
            .join("|"),
        )
        .unwrap();
    }

    let mut tokens = Vec::new();

    let mut last_token_end = 0;

    for captures in REGEX.captures_iter(input) {
        let token_type = if captures.name("literal").is_some() {
            Literal
        } else if captures.name("variable").is_some() {
            Variable
        } else if captures.name("operator").is_some() {
            Operator
        } else if captures.name("bracket").is_some() {
            Bracket
        } else if captures.name("separator").is_some() {
            Separator
        } else if captures.name("whitespace").is_some() {
            Whitespace
        } else {
            unreachable!()
        };

        let token_range = captures.get(0).unwrap().range();

        if last_token_end < token_range.start {
            tokens.push((input[last_token_end..token_range.start].to_owned(), Invalid));
        }

        last_token_end = token_range.end;

        tokens.push((input[token_range].to_owned(), token_type));
    }

    if last_token_end < input.len() {
        tokens.push((input[last_token_end..].to_owned(), Invalid));
    }

    tokens
}

#[derive(Completer, Helper, Hinter)]
pub struct InputHelper {}

impl Highlighter for InputHelper {
    fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
        &'s self,
        prompt: &'p str,
        _default: bool,
    ) -> Cow<'b, str> {
        Cow::Owned(Style::new().bold().paint(prompt).to_string())
    }

    fn highlight<'l>(&self, line: &'l str, pos: usize) -> Cow<'l, str> {
        use ansi_term::Colour::*;
        use TokenType::*;

        let matching_pos = if pos < line.len() {
            let line_bytes = line.as_bytes();

            let mut matching_pos = None;

            'outer: for (open, close) in [(b'(', b')'), (b'[', b']')] {
                let (range, open, close): (Box<dyn Iterator<Item = usize>>, _, _) =
                    if line_bytes[pos] == open {
                        (Box::new(pos + 1..line_bytes.len()), open, close)
                    } else if line_bytes[pos] == close {
                        (Box::new((0..pos).rev()), close, open)
                    } else {
                        continue;
                    };

                let mut closes_needed = 1;

                for i in range {
                    if line_bytes[i] == open {
                        closes_needed += 1;
                    } else if line_bytes[i] == close {
                        closes_needed -= 1;

                        if closes_needed == 0 {
                            matching_pos = Some(i);
                            break 'outer;
                        }
                    }
                }
            }

            matching_pos
        } else {
            None
        };

        let mut highlighted_line = String::new();

        let mut token_pos = 0;

        for (token, token_type) in tokenize(line) {
            let mut style = match token_type {
                Literal => Cyan.into(),
                Variable => Green.into(),
                Operator => Purple.into(),
                Bracket => Style::new(),
                Separator => Style::new(),
                Whitespace => Style::new(),
                Invalid => Red.into(),
            };

            if Some(token_pos) == matching_pos {
                style = style.bold();
            }

            token_pos += token.len();

            // https://github.com/rust-lang/rust-clippy/issues/9317
            #[allow(clippy::unnecessary_to_owned)]
            highlighted_line.push_str(&style.paint(token).to_string());
        }

        Cow::Owned(highlighted_line)
    }

    fn highlight_char(&self, _line: &str, _pos: usize) -> bool {
        true
    }
}

impl Validator for InputHelper {
    fn validate(&self, ctx: &mut ValidationContext) -> Result<ValidationResult> {
        // This implementation distinguishes only between "incomplete"
        // (unexpected end of input) and "valid" (everything else),
        // because actual input validation is performed by the REPL
        // as part of the regular input processing step.
        let input = ctx.input();

        if input.trim().is_empty() || input.ends_with('\n') {
            return Ok(ValidationResult::Valid(None));
        }

        if let Err(errors) = input.parse::<Expression>() {
            for error in errors {
                if error.reason() == &ErrorReason::Unexpected && error.found() == None {
                    return Ok(ValidationResult::Incomplete);
                }
            }
        }

        Ok(ValidationResult::Valid(None))
    }
}


================================================
FILE: savage/src/main.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

mod command;
mod help;
mod input;

use std::{
    collections::{HashMap, HashSet},
    fs,
    iter::FromIterator,
    rc::Rc,
};

use ansi_term::Style;
use ariadne::{Color, Fmt, Label, Report, ReportKind, Source};
use directories::ProjectDirs;
use lazy_static::lazy_static;
use rustyline::{error::ReadlineError, highlight::Highlighter, Editor};
use savage_core::{
    evaluate::{default_context, Error as EvaluateError},
    expression::{Expression, Vector},
    parse::{Error as ParseError, ErrorReason},
};

use crate::{
    command::Command,
    help::{show_help, FUNCTION_HELP_TEXTS, HELP_TEXT},
    input::InputHelper,
};

lazy_static! {
    static ref RESERVED_IDENTIFIERS: HashSet<String> =
        HashSet::from(["true", "false", "out"].map(str::to_owned));
}

fn format_parse_error(error: ParseError) -> Report {
    // Heavily based on https://github.com/zesterer/chumsky/blob/463226372cf293d45bd5df52bf25d5028243066e/examples/json.rs#L114-L173
    let message = if let ErrorReason::Custom(message) = error.reason() {
        message.clone()
    } else {
        format!(
            "{}, expected {}",
            if error.found().is_some() {
                "Unexpected token"
            } else {
                "Unexpected end of input"
            },
            if error.expected().len() == 0 {
                "something else".to_string()
            } else {
                error
                    .expected()
                    .map(|expected| match expected {
                        Some(expected) => expected.to_string(),
                        None => "end of input".to_string(),
                    })
                    .collect::<Vec<_>>()
                    .join(", ")
            },
        )
    };

    let report = Report::build(ReportKind::Error, (), error.span().start)
        .with_message(message)
        .with_label(
            Label::new(error.span())
                .with_message(match error.reason() {
                    ErrorReason::Custom(message) => message.clone(),
                    _ => format!(
                        "Unexpected {}",
                        error
                            .found()
                            .map(|c| format!("token {}", c.fg(Color::Red)))
                            .unwrap_or_else(|| "end of input".to_string()),
                    ),
                })
                .with_color(Color::Red),
        );

    let report = match error.reason() {
        ErrorReason::Unclosed { span, delimiter } => report.with_label(
            Label::new(span.clone())
                .with_message(format!(
                    "Unclosed delimiter {}",
                    delimiter.fg(Color::Yellow),
                ))
                .with_color(Color::Yellow),
        ),
        ErrorReason::Unexpected => report,
        ErrorReason::Custom(_) => report,
    };

    report.finish()
}

fn main() {
    use crate::command::Command::*;

    let history_path = ProjectDirs::from("com.worldwidemann", "", "Savage")
        .expect("unable to locate data directory")
        .data_dir()
        .join("history");

    let mut editor = Editor::new();

    editor.set_helper(Some(InputHelper {}));

    editor.load_history(&history_path).ok();

    println!(
        "Savage Computer Algebra System {}",
        env!("CARGO_PKG_VERSION"),
    );

    println!(
        "Enter {} for help, press {} to quit, {} to cancel evaluation",
        Style::new().bold().paint("?"),
        Style::new().bold().paint("Ctrl+D"),
        Style::new().bold().paint("Ctrl+C"),
    );

    let mut outputs = Vec::new();

    let mut context = default_context();

    context.insert(
        "out".to_owned(),
        Expression::Vector(Vector::from_vec(outputs.clone())),
    );

    'outer: loop {
        println!();

        match editor.readline("in: ") {
            Ok(line) => {
                let line = line.trim();

                if line.is_empty() {
                    continue;
                }

                editor.add_history_entry(line);

                match line.parse::<Command>() {
                    Ok(EvaluateExpression(expression)) => match expression.evaluate(&context) {
                        Ok(output) => {
                            println!(
                                "{}{}",
                                Style::new()
                                    .bold()
                                    .paint(format!("out[{}]: ", outputs.len())),
                                editor
                                    .helper()
                                    .unwrap()
                                    .highlight(&output.to_string(), usize::MAX),
                            );

                            outputs.push(output);

                            context.insert(
                                "out".to_owned(),
                                Expression::Vector(Vector::from_vec(outputs.clone())),
                            );
                        }
                        Err(error) => println!("Error: {:#?}", error),
                    },
                    Ok(DefineVariable(identifier, expression)) => {
                        if RESERVED_IDENTIFIERS.contains(&identifier) {
                            println!("Error: \"{}\" is a reserved identifier and cannot be used as a variable name.", identifier);
                            continue;
                        }

                        match expression.evaluate(&context) {
                            Ok(expression) => {
                                let variables = expression.variables();

                                if !variables.is_empty() {
                                    println!("Error: The assigned expression contains the undefined variable(s) {}.", Vec::from_iter(variables).join(", "));
                                    continue;
                                }

                                context.insert(identifier, expression);
                            }
                            Err(error) => println!("Error: {:#?}", error),
                        }
                    }
                    Ok(DefineFunction(identifier, argument_identifiers, expression)) => {
                        if RESERVED_IDENTIFIERS.contains(&identifier) {
                            println!("Error: \"{}\" is a reserved identifier and cannot be used as a function name.", identifier);
                            continue;
                        }

                        let mut inner_context = context.clone();

                        for argument_identifier in &argument_identifiers {
                            if RESERVED_IDENTIFIERS.contains(argument_identifier) {
                                println!("Error: \"{}\" is a reserved identifier and cannot be used as an argument name.", argument_identifier);
                                continue 'outer;
                            }

                            if argument_identifiers
                                .iter()
                                .filter(|&id| id == argument_identifier)
                                .count()
                                > 1
                            {
                                println!(
                                    "Error: The name \"{}\" is used for more than one argument.",
                                    argument_identifier,
                                );
                                continue 'outer;
                            }

                            inner_context.remove(argument_identifier);
                        }

                        match expression.evaluate(&inner_context) {
                            Ok(expression) => {
                                let mut variables = expression.variables();

                                for argument_identifier in &argument_identifiers {
                                    variables.remove(argument_identifier);
                                }

                                if !variables.is_empty() {
                                    println!("Error: The assigned expression contains the undefined variable(s) {}.", Vec::from_iter(variables).join(", "));
                                    continue;
                                }

                                context.insert(
                                    identifier.clone(),
                                    Expression::Function(
                                        identifier,
                                        Rc::new(move |self_expression, arguments, _| {
                                            if arguments.len() != argument_identifiers.len() {
                                                return Err(
                                                    EvaluateError::InvalidNumberOfArguments {
                                                        expression: self_expression.clone(),
                                                        min_number: argument_identifiers.len(),
                                                        max_number: argument_identifiers.len(),
                                                        given_number: arguments.len(),
                                                    },
                                                );
                                            }

                                            // Both the default context and the outer context the function is being
                                            // evaluated in can be ignored, since it was already checked that the
                                            // expression contains no variables other than the argument identifiers.
                                            let mut context = HashMap::new();

                                            for (identifier, argument) in
                                                argument_identifiers.iter().zip(arguments)
                                            {
                                                context
                                                    .insert(identifier.clone(), argument.clone());
                                            }

                                            expression.evaluate(&context)
                                        }),
                                    ),
                                );
                            }
                            Err(error) => println!("Error: {:#?}", error),
                        }
                    }
                    Ok(ShowHelp(function_name)) => {
                        if let Some(function_name) = function_name {
                            if let Some(function_help_text) =
                                FUNCTION_HELP_TEXTS.get(&function_name)
                            {
                                show_help(function_help_text.clone()).expect("unable to show help");
                            } else {
                                println!(
                                    "Error: No help text available for the function {}.",
                                    function_name,
                                );
                            }
                        } else {
                            show_help(HELP_TEXT.clone()).expect("unable to show help");
                        }
                    }
                    Err(errors) => {
                        for error in errors {
                            format_parse_error(error)
                                .print(Source::from(line))
                                .expect("unable to print parse error");
                        }
                    }
                }
            }
            Err(ReadlineError::Interrupted | ReadlineError::Eof) => {
                break;
            }
            Err(error) => {
                println!("Error: {:#?}", error);
                break;
            }
        }
    }

    fs::create_dir_all(
        history_path
            .parent()
            .expect("unable to determine parent directory of history file"),
    )
    .expect("unable to create data directory");

    editor
        .save_history(&history_path)
        .expect("unable to save input history");
}


================================================
FILE: savage_core/Cargo.toml
================================================
[package]
name = "savage_core"
version = "0.2.0"
authors = ["Philipp Emanuel Weidmann <pew@worldwidemann.com>"]
description = "A primitive computer algebra system (library)"
repository = "https://github.com/p-e-w/savage"
readme = "README.md"
license = "AGPL-3.0-or-later"
edition = "2021"

[dependencies]
num = "0.4.0"
nalgebra = "0.31.1"
permutohedron = "0.2.4"
primal = "0.3.0"
chumsky = "0.8.0"
derivative = "2.2.0"
savage_macros = { path = "../savage_macros", version = "0.1.0" }


================================================
FILE: savage_core/src/evaluate.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use std::collections::HashMap;

use num::{One, ToPrimitive, Zero};

use crate::{
    expression::{Complex, Expression, RationalRepresentation},
    functions::functions,
};

/// Error that occurred while trying to evaluate an expression.
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Error {
    /// Operation on an expression that the operation is not defined for.
    InvalidOperand {
        expression: Expression,
        operand: Expression,
    },
    /// Operation on two expressions that cannot be combined using the operation.
    IncompatibleOperands {
        expression: Expression,
        operand_1: Expression,
        operand_2: Expression,
    },
    /// Division by an expression that evaluates to zero (undefined).
    DivisionByZero {
        expression: Expression,
        dividend: Expression,
        divisor: Expression,
    },
    /// An expression that evaluates to zero raised to the power of
    /// another expression that evaluates to zero (undefined).
    ZeroToThePowerOfZero {
        expression: Expression,
        base: Expression,
        exponent: Expression,
    },
    /// Vector or matrix expression indexed by an expression that evaluates to
    /// an integer outside the range of valid indices for that vector or matrix.
    IndexOutOfBounds {
        expression: Expression,
        vector_or_matrix: Expression,
        index: Expression,
    },
    /// Function expression evaluated with a number of arguments
    /// that is invalid for the function.
    InvalidNumberOfArguments {
        expression: Expression,
        min_number: usize,
        max_number: usize,
        given_number: usize,
    },
    /// Function expression evaluated with an argument
    /// that is invalid for the function in that position.
    InvalidArgument {
        expression: Expression,
        argument: Expression,
    },
}

/// Returns an evaluation context populated with standard variable and function definitions.
pub fn default_context() -> HashMap<String, Expression> {
    let mut default_context = HashMap::new();

    default_context.insert(
        "i".to_owned(),
        Expression::Complex(Complex::i(), RationalRepresentation::Fraction),
    );

    for function in functions() {
        default_context.insert(
            function.metadata.name.to_owned(),
            Expression::Function(function.metadata.name.to_owned(), function.implementation),
        );
    }

    default_context
}

impl Expression {
    /// Returns the result of performing a single evaluation step on
    /// the unary operator expression `self` with operand `a`, or an error
    /// if the expression cannot be evaluated. The `context` argument can be
    /// used to set the values of variables by their identifiers.
    fn evaluate_step_unary(
        &self,
        a: &Self,
        context: &HashMap<String, Self>,
    ) -> Result<Self, Error> {
        use crate::expression::Expression::*;
        use crate::expression::Type::{Arithmetic, Boolean as Bool, Matrix as Mat, Number as Num};
        use Error::*;

        let a_original = a;

        let a = a.evaluate_step(context)?;

        match (self, a.typ()) {
            (Negation(_), Bool(_)) | (Not(_), Num(_, _) | Mat(_) | Arithmetic) => {
                Err(InvalidOperand {
                    expression: self.clone(),
                    operand: a_original.clone(),
                })
            }

            (Negation(_), Num(a, representation)) => Ok(Complex(-a, representation)),
            (Negation(_), Mat(a)) => Ok(Matrix(-a)),
            (Negation(_), _) => Ok(Negation(Box::new(a))),

            (Not(_), Bool(Some(a))) => Ok(Boolean(!a)),
            (Not(_), _) => Ok(Not(Box::new(a))),

            (
                Variable(_)
                | Function(_, _)
                | FunctionValue(_, _)
                | Integer(_)
                | Rational(_, _)
                | Complex(_, _)
                | Vector(_)
                | VectorElement(_, _)
                | Matrix(_)
                | MatrixElement(_, _, _)
                | Boolean(_)
                | Sum(_, _)
                | Difference(_, _)
                | Product(_, _)
                | Quotient(_, _)
                | Remainder(_, _)
                | Power(_, _)
                | Equal(_, _)
                | NotEqual(_, _)
                | LessThan(_, _)
                | LessThanOrEqual(_, _)
                | GreaterThan(_, _)
                | GreaterThanOrEqual(_, _)
                | And(_, _)
                | Or(_, _),
                _,
            ) => unreachable!(),
        }
    }

    /// Returns the result of performing a single evaluation step on
    /// the binary operator expression `self` with operands `a` and `b`,
    /// or an error if the expression cannot be evaluated. The `context`
    /// argument can be used to set the values of variables by their
    /// identifiers.
    fn evaluate_step_binary(
        &self,
        a: &Self,
        b: &Self,
        context: &HashMap<String, Self>,
    ) -> Result<Self, Error> {
        use crate::expression::Expression::*;
        use crate::expression::Type::{Arithmetic, Boolean as Bool, Matrix as Mat, Number as Num};
        use Error::*;

        let a_original = a;
        let b_original = b;

        let a = a.evaluate_step(context)?;
        let b = b.evaluate_step(context)?;

        let a_evaluated = &a;
        let b_evaluated = &b;

        match (self, a.typ(), b.typ()) {
            (
                Sum(_, _)
                | Difference(_, _)
                | Product(_, _)
                | Quotient(_, _)
                | Remainder(_, _)
                | Power(_, _),
                Bool(_),
                _,
            )
            | (
                LessThan(_, _)
                | LessThanOrEqual(_, _)
                | GreaterThan(_, _)
                | GreaterThanOrEqual(_, _),
                Mat(_) | Bool(_),
                _,
            )
            | (And(_, _) | Or(_, _), Num(_, _) | Mat(_) | Arithmetic, _) => Err(InvalidOperand {
                expression: self.clone(),
                operand: a_original.clone(),
            }),

            (
                Sum(_, _)
                | Difference(_, _)
                | Product(_, _)
                | Quotient(_, _)
                | Remainder(_, _)
                | Power(_, _),
                _,
                Bool(_),
            )
            | (
                LessThan(_, _)
                | LessThanOrEqual(_, _)
                | GreaterThan(_, _)
                | GreaterThanOrEqual(_, _),
                _,
                Mat(_) | Bool(_),
            )
            | (And(_, _) | Or(_, _), _, Num(_, _) | Mat(_) | Arithmetic) => Err(InvalidOperand {
                expression: self.clone(),
                operand: b_original.clone(),
            }),

            (Sum(_, _) | Difference(_, _) | Equal(_, _) | NotEqual(_, _), Num(_, _), Mat(_))
            | (Sum(_, _) | Difference(_, _) | Equal(_, _) | NotEqual(_, _), Mat(_), Num(_, _))
            | (Equal(_, _) | NotEqual(_, _), Num(_, _) | Mat(_), Bool(_))
            | (Equal(_, _) | NotEqual(_, _), Bool(_), Num(_, _) | Mat(_)) => {
                Err(IncompatibleOperands {
                    expression: self.clone(),
                    operand_1: a_original.clone(),
                    operand_2: b_original.clone(),
                })
            }

            (
                Sum(_, _)
                | Difference(_, _)
                | Product(_, _)
                | Quotient(_, _)
                | Remainder(_, _)
                | Power(_, _)
                | Equal(_, _)
                | NotEqual(_, _)
                | LessThan(_, _)
                | LessThanOrEqual(_, _)
                | GreaterThan(_, _)
                | GreaterThanOrEqual(_, _),
                Num(a, a_representation),
                Num(b, b_representation),
            ) => {
                let representation = a_representation.merge(b_representation);

                match self {
                    Sum(_, _) => Ok(Complex(a + b, representation)),
                    Difference(_, _) => Ok(Complex(a - b, representation)),
                    Product(_, _) => Ok(Complex(a * b, representation)),
                    Quotient(_, _) | Remainder(_, _) => {
                        if b.is_zero() {
                            Err(DivisionByZero {
                                expression: self.clone(),
                                dividend: a_original.clone(),
                                divisor: b_original.clone(),
                            })
                        } else {
                            Ok(Complex(
                                match self {
                                    Quotient(_, _) => a / b,
                                    Remainder(_, _) => a % b,
                                    _ => unreachable!(),
                                },
                                representation,
                            ))
                        }
                    }
                    Power(_, _) => {
                        if a.is_zero() && b.is_zero() {
                            Err(ZeroToThePowerOfZero {
                                expression: self.clone(),
                                base: a_original.clone(),
                                exponent: b_original.clone(),
                            })
                        } else if let Some(b) = b.to_i32() {
                            Ok(Complex(a.powi(b), representation))
                        } else {
                            // TODO
                            Ok(Power(
                                Box::new(a_evaluated.clone()),
                                Box::new(b_evaluated.clone()),
                            ))
                        }
                    }
                    Equal(_, _) => Ok(Boolean(a == b)),
                    NotEqual(_, _) => Ok(Boolean(a != b)),
                    LessThan(_, _)
                    | LessThanOrEqual(_, _)
                    | GreaterThan(_, _)
                    | GreaterThanOrEqual(_, _) => {
                        if !a.im.is_zero() {
                            Err(InvalidOperand {
                                expression: self.clone(),
                                operand: a_original.clone(),
                            })
                        } else if !b.im.is_zero() {
                            Err(InvalidOperand {
                                expression: self.clone(),
                                operand: b_original.clone(),
                            })
                        } else {
                            let a = a.re;
                            let b = b.re;

                            Ok(Boolean(match self {
                                LessThan(_, _) => a < b,
                                LessThanOrEqual(_, _) => a <= b,
                                GreaterThan(_, _) => a > b,
                                GreaterThanOrEqual(_, _) => a >= b,
                                _ => unreachable!(),
                            }))
                        }
                    }
                    _ => unreachable!(),
                }
            }

            (Sum(_, _) | Difference(_, _), Mat(a), Mat(b)) => {
                if a.shape() == b.shape() {
                    Ok(Matrix(match self {
                        Sum(_, _) => a + b,
                        Difference(_, _) => a - b,
                        _ => unreachable!(),
                    }))
                } else {
                    Err(IncompatibleOperands {
                        expression: self.clone(),
                        operand_1: a_original.clone(),
                        operand_2: b_original.clone(),
                    })
                }
            }

            (Product(_, _), Mat(a), Mat(b)) => {
                if a.is_empty() && b.is_empty() {
                    Ok(Matrix(a))
                } else if !a.is_empty() && !b.is_empty() && a.ncols() == b.nrows() {
                    Ok(Matrix(crate::expression::Matrix::from_fn(
                        a.nrows(),
                        b.ncols(),
                        |i, j| {
                            (0..a.ncols())
                                .map(|k| a[(i, k)].clone() * b[(k, j)].clone())
                                .reduce(|a, b| a + b)
                                .unwrap()
                        },
                    )))
                } else {
                    Err(IncompatibleOperands {
                        expression: self.clone(),
                        operand_1: a_original.clone(),
                        operand_2: b_original.clone(),
                    })
                }
            }

            (Product(_, _), Mat(a), _) => Ok(Matrix(a.map(|element| element * b.clone()))),
            (Product(_, _), _, Mat(b)) => Ok(Matrix(b.map(|element| a.clone() * element))),

            (Equal(_, _), Bool(Some(a)), Bool(Some(b))) => Ok(Boolean(a == b)),
            (NotEqual(_, _), Bool(Some(a)), Bool(Some(b))) => Ok(Boolean(a != b)),
            (And(_, _), Bool(Some(a)), Bool(Some(b))) => Ok(Boolean(a && b)),
            (Or(_, _), Bool(Some(a)), Bool(Some(b))) => Ok(Boolean(a || b)),

            (Sum(_, _), _, _) => Ok(Sum(Box::new(a), Box::new(b))), // TODO
            (Difference(_, _), _, _) => Ok(Difference(Box::new(a), Box::new(b))), // TODO
            (Product(_, _), _, _) => Ok(Product(Box::new(a), Box::new(b))), // TODO
            (Quotient(_, _), _, _) => Ok(Quotient(Box::new(a), Box::new(b))), // TODO
            (Remainder(_, _), _, _) => Ok(Remainder(Box::new(a), Box::new(b))), // TODO
            (Power(_, _), _, _) => Ok(Power(Box::new(a), Box::new(b))), // TODO
            (Equal(_, _), _, _) => Ok(Equal(Box::new(a), Box::new(b))), // TODO
            (NotEqual(_, _), _, _) => Ok(NotEqual(Box::new(a), Box::new(b))), // TODO
            (LessThan(_, _), _, _) => Ok(LessThan(Box::new(a), Box::new(b))), // TODO
            (LessThanOrEqual(_, _), _, _) => Ok(LessThanOrEqual(Box::new(a), Box::new(b))), // TODO
            (GreaterThan(_, _), _, _) => Ok(GreaterThan(Box::new(a), Box::new(b))), // TODO
            (GreaterThanOrEqual(_, _), _, _) => Ok(GreaterThanOrEqual(Box::new(a), Box::new(b))), // TODO
            (And(_, _), _, _) => Ok(And(Box::new(a), Box::new(b))), // TODO
            (Or(_, _), _, _) => Ok(Or(Box::new(a), Box::new(b))),   // TODO

            (
                Variable(_)
                | Function(_, _)
                | FunctionValue(_, _)
                | Integer(_)
                | Rational(_, _)
                | Complex(_, _)
                | Vector(_)
                | VectorElement(_, _)
                | Matrix(_)
                | MatrixElement(_, _, _)
                | Boolean(_)
                | Negation(_)
                | Not(_),
                _,
                _,
            ) => unreachable!(),
        }
    }

    /// Returns the result of performing a single evaluation step on the expression,
    /// or an error if the expression cannot be evaluated. The `context` argument
    /// can be used to set the values of variables by their identifiers.
    fn evaluate_step(&self, context: &HashMap<String, Self>) -> Result<Self, Error> {
        use crate::expression::Expression::*;
        use crate::expression::Type::{
            Boolean as Bool, Function as Fun, Matrix as Mat, Number as Num,
        };
        use Error::*;

        let expression = self.simplify();

        match &expression {
            Variable(identifier) => context
                .get(identifier)
                .map_or_else(|| Ok(expression), |x| x.evaluate_step(context)),
            Function(_, _) => Ok(expression),
            FunctionValue(function, arguments) => {
                let function_original = function;

                let function = function.evaluate_step(context)?;

                let mut arguments_evaluated = Vec::new();

                for argument in arguments {
                    arguments_evaluated.push(argument.evaluate_step(context)?);
                }

                match function.typ() {
                    Num(_, _) | Mat(_) | Bool(_) => Err(InvalidOperand {
                        expression: expression.clone(),
                        operand: *function_original.clone(),
                    }),

                    Fun(_, f) => f(&expression, &arguments_evaluated, context),

                    _ => Ok(FunctionValue(Box::new(function), arguments_evaluated)),
                }
            }
            Integer(_) => Ok(expression),
            Rational(x, _) => Ok(if x.denom().is_one() {
                Integer(x.numer().clone())
            } else {
                expression
            }),
            Complex(z, representation) => Ok(if z.im.is_zero() {
                Rational(z.re.clone(), *representation)
            } else {
                expression
            }),
            Vector(v) => {
                let mut elements = Vec::new();

                for element in v.iter() {
                    elements.push(element.evaluate_step(context)?);
                }

                Ok(Vector(crate::expression::Vector::from_vec(elements)))
            }
            VectorElement(vector, i) => {
                let vector_original = vector;
                let i_original = i;

                let vector = vector.evaluate_step(context)?;
                let i = i.evaluate_step(context)?;

                match (vector.typ(), i.typ()) {
                    (Num(_, _) | Bool(_), _) => Err(InvalidOperand {
                        expression: expression.clone(),
                        operand: *vector_original.clone(),
                    }),

                    (_, Mat(_) | Bool(_)) => Err(InvalidOperand {
                        expression: expression.clone(),
                        operand: *i_original.clone(),
                    }),

                    (Mat(vector), Num(i, _)) => {
                        if vector.ncols() != 1 {
                            Err(InvalidOperand {
                                expression: expression.clone(),
                                operand: *vector_original.clone(),
                            })
                        } else if let Some(i) = i.to_usize() {
                            if i >= vector.nrows() {
                                Err(IndexOutOfBounds {
                                    expression: expression.clone(),
                                    vector_or_matrix: *vector_original.clone(),
                                    index: *i_original.clone(),
                                })
                            } else {
                                Ok(vector[(i, 0)].clone())
                            }
                        } else {
                            Err(InvalidOperand {
                                expression: expression.clone(),
                                operand: *i_original.clone(),
                            })
                        }
                    }

                    _ => Ok(VectorElement(Box::new(vector), Box::new(i))),
                }
            }
            Matrix(m) => {
                let mut columns = Vec::new();

                for column in m.column_iter() {
                    let mut elements = Vec::new();

                    for element in column.iter() {
                        elements.push(element.evaluate_step(context)?);
                    }

                    columns.push(crate::expression::Vector::from_vec(elements));
                }

                Ok(if columns.is_empty() {
                    Vector(crate::expression::Vector::from_vec(Vec::new()))
                } else if columns.len() == 1 {
                    Vector(columns.remove(0))
                } else {
                    Matrix(crate::expression::Matrix::from_columns(&columns))
                })
            }
            MatrixElement(matrix, i, j) => {
                let matrix_original = matrix;
                let i_original = i;
                let j_original = j;

                let matrix = matrix.evaluate_step(context)?;
                let i = i.evaluate_step(context)?;
                let j = j.evaluate_step(context)?;

                match (matrix.typ(), i.typ(), j.typ()) {
                    (Num(_, _) | Bool(_), _, _) => Err(InvalidOperand {
                        expression: expression.clone(),
                        operand: *matrix_original.clone(),
                    }),

                    (_, Mat(_) | Bool(_), _) => Err(InvalidOperand {
                        expression: expression.clone(),
                        operand: *i_original.clone(),
                    }),

                    (_, _, Mat(_) | Bool(_)) => Err(InvalidOperand {
                        expression: expression.clone(),
                        operand: *j_original.clone(),
                    }),

                    (Mat(matrix), Num(i, _), Num(j, _)) => {
                        if let Some(i) = i.to_usize() {
                            if let Some(j) = j.to_usize() {
                                if i >= matrix.nrows() {
                                    Err(IndexOutOfBounds {
                                        expression: expression.clone(),
                                        vector_or_matrix: *matrix_original.clone(),
                                        index: *i_original.clone(),
                                    })
                                } else if j >= matrix.ncols() {
                                    Err(IndexOutOfBounds {
                                        expression: expression.clone(),
                                        vector_or_matrix: *matrix_original.clone(),
                                        index: *j_original.clone(),
                                    })
                                } else {
                                    Ok(matrix[(i, j)].clone())
                                }
                            } else {
                                Err(InvalidOperand {
                                    expression: expression.clone(),
                                    operand: *j_original.clone(),
                                })
                            }
                        } else {
                            Err(InvalidOperand {
                                expression: expression.clone(),
                                operand: *i_original.clone(),
                            })
                        }
                    }

                    _ => Ok(MatrixElement(Box::new(matrix), Box::new(i), Box::new(j))),
                }
            }
            Boolean(_) => Ok(expression),
            Negation(a) => expression.evaluate_step_unary(a, context),
            Not(a) => expression.evaluate_step_unary(a, context),
            Sum(a, b) => expression.evaluate_step_binary(a, b, context),
            Difference(a, b) => expression.evaluate_step_binary(a, b, context),
            Product(a, b) => expression.evaluate_step_binary(a, b, context),
            Quotient(a, b) => expression.evaluate_step_binary(a, b, context),
            Remainder(a, b) => expression.evaluate_step_binary(a, b, context),
            Power(a, b) => expression.evaluate_step_binary(a, b, context),
            Equal(a, b) => expression.evaluate_step_binary(a, b, context),
            NotEqual(a, b) => expression.evaluate_step_binary(a, b, context),
            LessThan(a, b) => expression.evaluate_step_binary(a, b, context),
            LessThanOrEqual(a, b) => expression.evaluate_step_binary(a, b, context),
            GreaterThan(a, b) => expression.evaluate_step_binary(a, b, context),
            GreaterThanOrEqual(a, b) => expression.evaluate_step_binary(a, b, context),
            And(a, b) => expression.evaluate_step_binary(a, b, context),
            Or(a, b) => expression.evaluate_step_binary(a, b, context),
        }
    }

    /// Returns the result of evaluating the expression, or an error
    /// if the expression cannot be evaluated. The `context` argument
    /// can be used to set the values of variables by their identifiers.
    pub fn evaluate(&self, context: &HashMap<String, Self>) -> Result<Self, Error> {
        let mut old_expression: Self = self.clone();

        loop {
            let new_expression = old_expression.evaluate_step(context)?;

            if new_expression == old_expression {
                return Ok(new_expression);
            }

            old_expression = new_expression;
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::evaluate::default_context;
    use crate::expression::Expression;

    #[track_caller]
    fn t(expression: &str, result: &str) {
        assert_eq!(
            expression
                .parse::<Expression>()
                .unwrap()
                .evaluate(&default_context())
                .unwrap()
                .to_string(),
            result,
        );
    }

    #[test]
    fn arithmetic() {
        t("-(-1)", "1");
        t("-0", "0");

        t("1 + 2", "3");
        t("1 + -1", "0");
        t("1/2 + 0.5", "1");
        t(
            "123456789987654321 + 987654321123456789",
            "1111111111111111110",
        );

        t("1 - 2", "-1");
        t("1 - -1", "2");
        t("1/2 - 0.5", "0");
        t(
            "123456789987654321 - 987654321123456789",
            "-864197531135802468",
        );

        t("1 * 2", "2");
        t("1 * -1", "-1");
        t("1/2 * 0.5", "0.25");
        t(
            "123456789987654321 * 987654321123456789",
            "121932632103337905662094193112635269",
        );

        t("1 / 2", "1/2");
        t("1 / -1", "-1");
        t("1/2 / 0.5", "1");
        t(
            "123456789987654321 / 987654321123456789",
            "101010101/808080809",
        );

        t("4 % 2", "0");
        t("0 % 2", "0");
        t("5 % 2", "1");
        t("-5 % 2", "-1");
        t("-5 % -2", "-1");
        t("0.75 % (1/4)", "0");
        t("0.75 % (1/3)", "1/12");
        t("987654321123456789 % 123456789987654321", "1222222221");

        t("i ^ 2", "-1");
        t("2 ^ 3", "8");
        t("2 ^ (-3)", "1/8");
        t("-2 ^ 4", "-16");
        t("(-2) ^ 4", "16");
        t("0.5 ^ 4", "0.0625");
        t(
            "987654321123456789 ^ 5",
            "939777062588963894467852986656442266299580252508947542802086985660852317355013741720482949",
        );
        t(
            "3 ^ 4 ^ 5",
            "373391848741020043532959754184866588225409776783734007750636931722079040617265251229993688938803977220468765065431475158108727054592160858581351336982809187314191748594262580938807019951956404285571818041046681288797402925517668012340617298396574731619152386723046235125934896058590588284654793540505936202376547807442730582144527058988756251452817793413352141920744623027518729185432862375737063985485319476416926263819972887006907013899256524297198527698749274196276811060702333710356481",
        );
    }

    #[test]
    fn linear_algebra() {
        t("[1] + [2]", "[3]");
        t("[1] - [2]", "[-1]");
        t("[1] * [2]", "[2]");
        t("[1] * 2", "[2]");
        t("1 * [2]", "[2]");

        t("[1, 2] + [3, 4]", "[4, 6]");
        t("[1, 2] - [3, 4]", "[-2, -2]");
        t("[1, 2] * [[3, 4]]", "[[3, 4], [6, 8]]");
        t("[[1, 2]] * [3, 4]", "[11]");
        t("2 * [3, 4]", "[6, 8]");
        t("[2, 3] * 4", "[8, 12]");

        t(
            "[[a, b], [c, d], [e, f]] * [[5, 6], [7, 8]]",
            "[[a * 5 + b * 7, a * 6 + b * 8], [c * 5 + d * 7, c * 6 + d * 8], [e * 5 + f * 7, e * 6 + f * 8]]",
        );
    }

    #[test]
    fn indices() {
        t("[a][0]", "a");
        t("[a, b, c][2]", "c");
        t("[1 + 2, 2 + 3, 3 + 4, 4 + 5][1 + 2]", "9");

        t("[[a]][0, 0]", "a");
        t("[[a, b, c], [d, e, f]][1, 2]", "f");
        t("[[1 + 2, 2 + 3], [3 + 4, 4 + 5]][0 + 0, 0 + 1]", "5");
    }

    #[test]
    fn logic() {
        t("!true", "false");
        t("!false", "true");

        t("true && true", "true");
        t("true && false", "false");
        t("false && true", "false");
        t("false && false", "false");

        t("true || true", "true");
        t("true || false", "true");
        t("false || true", "true");
        t("false || false", "false");
    }

    #[test]
    fn comparisons() {
        t("0 == 0", "true");
        t("0 == 0.0", "true");
        t("0.5 == 1/2", "true");
        t("1/2 == 2/4", "true");
        t("3 ^ 4 ^ 5 == 5 ^ 4 ^ 3", "false");

        t("0 != 0", "false");
        t("0 != 0.0", "false");
        t("0.5 != 1/2", "false");
        t("1/2 != 2/4", "false");
        t("3 ^ 4 ^ 5 != 5 ^ 4 ^ 3", "true");

        t("0 < 0", "false");
        t("0 < 0.0", "false");
        t("0.5 < 1/2", "false");
        t("1/2 < 2/4", "false");
        t("3 ^ 4 ^ 5 < 5 ^ 4 ^ 3", "false");

        t("0 <= 0", "true");
        t("0 <= 0.0", "true");
        t("0.5 <= 1/2", "true");
        t("1/2 <= 2/4", "true");
        t("3 ^ 4 ^ 5 <= 5 ^ 4 ^ 3", "false");

        t("0 > 0", "false");
        t("0 > 0.0", "false");
        t("0.5 > 1/2", "false");
        t("1/2 > 2/4", "false");
        t("3 ^ 4 ^ 5 > 5 ^ 4 ^ 3", "true");

        t("0 >= 0", "true");
        t("0 >= 0.0", "true");
        t("0.5 >= 1/2", "true");
        t("1/2 >= 2/4", "true");
        t("3 ^ 4 ^ 5 >= 5 ^ 4 ^ 3", "true");

        t("true == true", "true");
        t("true == false", "false");
        t("false == true", "false");
        t("false == false", "true");

        t("true != true", "false");
        t("true != false", "true");
        t("false != true", "true");
        t("false != false", "false");
    }
}


================================================
FILE: savage_core/src/expression.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use std::{
    collections::{HashMap, HashSet},
    rc::Rc,
};

use derivative::*;
use num::{Signed, Zero};

use crate::evaluate::Error;

/// Function implementation.
pub type Function =
    dyn Fn(&Expression, &[Expression], &HashMap<String, Expression>) -> Result<Expression, Error>;

/// Arbitrary-precision integer.
pub type Integer = num::bigint::BigInt;

/// Arbitrary-precision rational number.
pub type Rational = num::rational::Ratio<Integer>;

/// Arbitrary-precision complex number (i.e. real and imaginary parts are arbitrary-precision rational numbers).
pub type Complex = num::complex::Complex<Rational>;

/// Column vector with expressions as components.
pub type Vector = nalgebra::DVector<Expression>;

/// Column-major matrix with expressions as components.
pub type Matrix = nalgebra::DMatrix<Expression>;

/// Preferred representation when printing a rational number.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum RationalRepresentation {
    /// Fraction (numerator/denominator).
    Fraction,
    /// Decimal, falling back to fraction representation
    /// if the number cannot be represented as a finite decimal.
    Decimal,
}

impl RationalRepresentation {
    /// Returns the preferred representation for the result of an operation
    /// on two numbers with representations `self` and `other`.
    pub(crate) fn merge(self, other: Self) -> Self {
        use RationalRepresentation::*;

        if self == Decimal || other == Decimal {
            Decimal
        } else {
            Fraction
        }
    }
}

/// Symbolic expression.
#[derive(Derivative)]
#[derivative(PartialEq, Eq, Clone, Debug)]
pub enum Expression {
    /// Variable with identifier.
    Variable(String),
    /// Function with identifier and implementation.
    Function(
        String,
        #[derivative(PartialEq = "ignore", Debug = "ignore")] Rc<Function>,
    ),
    /// Value of a function expression at the given arguments.
    FunctionValue(Box<Self>, Vec<Self>),
    /// Integer.
    Integer(Integer),
    /// Rational number with preferred representation.
    Rational(Rational, RationalRepresentation),
    /// Complex number with preferred representation for real and imaginary parts.
    Complex(Complex, RationalRepresentation),
    /// Column vector.
    Vector(Vector),
    /// Element of a column vector expression given by an index expression.
    VectorElement(Box<Self>, Box<Self>),
    /// Column-major matrix.
    Matrix(Matrix),
    /// Element of a column-major matrix expression given by row and column index expressions.
    MatrixElement(Box<Self>, Box<Self>, Box<Self>),
    /// Boolean value.
    Boolean(bool),
    /// Arithmetic negation of an expression.
    Negation(Box<Self>),
    /// Logical negation (NOT) of an expression.
    Not(Box<Self>),
    /// Sum of two expressions.
    Sum(Box<Self>, Box<Self>),
    /// Difference of two expressions.
    Difference(Box<Self>, Box<Self>),
    /// Product of two expressions.
    Product(Box<Self>, Box<Self>),
    /// Quotient of two expressions.
    Quotient(Box<Self>, Box<Self>),
    /// Remainder of the Euclidean division of the first expression by the second.
    Remainder(Box<Self>, Box<Self>),
    /// The first expression raised to the power of the second.
    Power(Box<Self>, Box<Self>),
    /// Whether two expressions are equal.
    Equal(Box<Self>, Box<Self>),
    /// Whether two expressions are not equal.
    NotEqual(Box<Self>, Box<Self>),
    /// Whether the first expression is less than the second.
    LessThan(Box<Self>, Box<Self>),
    /// Whether the first expression is less than or equal to the second.
    LessThanOrEqual(Box<Self>, Box<Self>),
    /// Whether the first expression is greater than the second.
    GreaterThan(Box<Self>, Box<Self>),
    /// Whether the first expression is greater than or equal to the second.
    GreaterThanOrEqual(Box<Self>, Box<Self>),
    /// Logical conjunction (AND) of two expressions.
    And(Box<Self>, Box<Self>),
    /// Logical disjunction (OR) of two expressions.
    Or(Box<Self>, Box<Self>),
}

/// Basic expression type designed to make evaluating expressions easier.
#[derive(Derivative)]
#[derivative(PartialEq, Eq, Clone, Debug)]
pub(crate) enum Type {
    /// Function with identifier and implementation.
    Function(
        String,
        #[derivative(PartialEq = "ignore", Debug = "ignore")] Rc<Function>,
    ),
    /// Number with preferred representation for rational parts.
    Number(Complex, RationalRepresentation),
    /// Column-major matrix.
    Matrix(Matrix),
    /// Boolean expression with value (if available).
    Boolean(Option<bool>),
    /// Arithmetic expression (in particular, this expression does *not* have a boolean value).
    Arithmetic,
    /// Expression that cannot be assigned to any of the above types with certainty.
    Unknown,
}

/// Associativity of an operator expression.
#[allow(clippy::enum_variant_names)]
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub(crate) enum Associativity {
    /// `a OP b OP c == (a OP b) OP c`.
    LeftAssociative,
    /// `a OP b OP c == a OP (b OP c)`.
    RightAssociative,
    /// `a OP b OP c == (a OP b) OP c == a OP (b OP c)`.
    Associative,
}

impl Expression {
    /// Returns the basic type of the expression.
    pub(crate) fn typ(&self) -> Type {
        use Expression::*;
        use RationalRepresentation::*;
        use Type::{
            Arithmetic, Boolean as Bool, Function as Fun, Matrix as Mat, Number as Num, Unknown,
        };

        match self {
            Variable(_) => Unknown,
            Function(identifier, f) => Fun(identifier.clone(), f.clone()),
            FunctionValue(_, _) => Unknown,
            Integer(n) => Num(self::Rational::from_integer(n.clone()).into(), Fraction),
            Rational(x, representation) => Num(x.into(), *representation),
            Complex(z, representation) => Num(z.clone(), *representation),
            Vector(v) => Mat(self::Matrix::from_columns(&[v.clone()])),
            VectorElement(_, _) => Unknown,
            Matrix(m) => Mat(m.clone()),
            MatrixElement(_, _, _) => Unknown,
            Boolean(boolean) => Bool(Some(*boolean)),
            Negation(_) => Arithmetic,
            Not(_) => Bool(None),
            Sum(_, _) => Arithmetic,
            Difference(_, _) => Arithmetic,
            Product(_, _) => Arithmetic,
            Quotient(_, _) => Arithmetic,
            Remainder(_, _) => Arithmetic,
            Power(_, _) => Arithmetic,
            Equal(_, _) => Bool(None),
            NotEqual(_, _) => Bool(None),
            LessThan(_, _) => Bool(None),
            LessThanOrEqual(_, _) => Bool(None),
            GreaterThan(_, _) => Bool(None),
            GreaterThanOrEqual(_, _) => Bool(None),
            And(_, _) => Bool(None),
            Or(_, _) => Bool(None),
        }
    }

    /// Returns the precedence (as an integer intended for comparison)
    /// and associativity of the expression. For unary or non-operator
    /// expressions, to which the concept of associativity doesn't apply,
    /// `Associative` is returned.
    pub(crate) fn precedence_and_associativity(&self) -> (isize, Associativity) {
        use Associativity::*;
        use Expression::*;

        match self {
            Variable(_) => (isize::MAX, Associative),
            Function(_, _) => (isize::MAX, Associative),
            FunctionValue(_, _) => (5, Associative),
            Integer(n) => {
                if n.is_negative() {
                    (2, Associative)
                } else {
                    (isize::MAX, Associative)
                }
            }
            Rational(x, _) => {
                if self.to_string().contains('/') {
                    (2, LeftAssociative)
                } else if x.is_negative() {
                    (2, Associative)
                } else {
                    (isize::MAX, Associative)
                }
            }
            Complex(z, _) => {
                if !z.re.is_zero() && !z.im.is_zero() {
                    if self.to_string().contains('+') {
                        (1, Associative)
                    } else {
                        (1, LeftAssociative)
                    }
                } else if self.to_string().contains('/') {
                    (2, LeftAssociative)
                } else if z.re.is_negative() || !z.im.is_zero() {
                    (2, Associative)
                } else {
                    (isize::MAX, Associative)
                }
            }
            Vector(_) => (isize::MAX, Associative),
            VectorElement(_, _) => (5, Associative),
            Matrix(_) => (isize::MAX, Associative),
            MatrixElement(_, _, _) => (5, Associative),
            Boolean(_) => (isize::MAX, Associative),
            Negation(_) => (3, Associative),
            Not(_) => (3, Associative),
            Sum(_, _) => (1, Associative),
            Difference(_, _) => (1, LeftAssociative),
            Product(_, _) => (2, Associative),
            Quotient(_, _) => (2, LeftAssociative),
            Remainder(_, _) => (2, LeftAssociative),
            Power(_, _) => (4, RightAssociative),
            Equal(_, _) => (0, Associative),
            NotEqual(_, _) => (0, Associative),
            LessThan(_, _) => (0, Associative),
            LessThanOrEqual(_, _) => (0, Associative),
            GreaterThan(_, _) => (0, Associative),
            GreaterThanOrEqual(_, _) => (0, Associative),
            And(_, _) => (-1, Associative),
            Or(_, _) => (-2, Associative),
        }
    }

    /// Returns the precedence (as an integer intended for comparison) of the expression.
    pub(crate) fn precedence(&self) -> isize {
        self.precedence_and_associativity().0
    }

    /// Returns the associativity of the expression.
    /// For unary or non-operator expressions, to which the concept
    /// of associativity doesn't apply, `Associative` is returned.
    pub(crate) fn associativity(&self) -> Associativity {
        self.precedence_and_associativity().1
    }

    /// Returns all sub-expressions that the expression contains.
    /// The returned list is built recursively and thus includes sub-expressions
    /// of sub-expressions and so on, as well as the expression itself.
    pub(crate) fn parts(&self) -> Vec<Self> {
        use Expression::*;

        let mut parts = vec![self.clone()];

        match self {
            Variable(_) => {}
            Function(_, _) => {}
            FunctionValue(function, arguments) => {
                parts.append(&mut function.parts());

                for argument in arguments {
                    parts.append(&mut argument.parts());
                }
            }
            Integer(_) => {}
            Rational(_, _) => {}
            Complex(_, _) => {}
            Vector(v) => {
                for element in v.iter() {
                    parts.append(&mut element.parts());
                }
            }
            VectorElement(vector, i) => {
                parts.append(&mut vector.parts());
                parts.append(&mut i.parts());
            }
            Matrix(m) => {
                for element in m.iter() {
                    parts.append(&mut element.parts());
                }
            }
            MatrixElement(matrix, i, j) => {
                parts.append(&mut matrix.parts());
                parts.append(&mut i.parts());
                parts.append(&mut j.parts());
            }
            Boolean(_) => {}
            Negation(a) | Not(a) => {
                parts.append(&mut a.parts());
            }
            Sum(a, b)
            | Difference(a, b)
            | Product(a, b)
            | Quotient(a, b)
            | Remainder(a, b)
            | Power(a, b)
            | Equal(a, b)
            | NotEqual(a, b)
            | LessThan(a, b)
            | LessThanOrEqual(a, b)
            | GreaterThan(a, b)
            | GreaterThanOrEqual(a, b)
            | And(a, b)
            | Or(a, b) => {
                parts.append(&mut a.parts());
                parts.append(&mut b.parts());
            }
        }

        parts
    }

    /// Returns the identifiers of all variables that the expression contains.
    pub fn variables(&self) -> HashSet<String> {
        let mut identifiers = HashSet::new();

        for part in self.parts() {
            if let Self::Variable(identifier) = part {
                identifiers.insert(identifier);
            }
        }

        identifiers
    }
}


================================================
FILE: savage_core/src/functions/combinatorics.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use num::range_inclusive;
use savage_macros::function;

use crate::{expression::Integer, functions::NonNegativeInteger};

#[function(
    name = "factorial",
    description = "factorial of a non-negative integer",
    examples = r#"[
        ("factorial(0)", "1"),
        ("factorial(1)", "1"),
        ("factorial(4)", "24"),
        ("factorial(10)", "3628800"),
    ]"#,
    categories = r#"[
        "combinatorics",
    ]"#
)]
fn factorial(n: NonNegativeInteger) -> Integer {
    range_inclusive::<Integer>(1.into(), n).product()
}


================================================
FILE: savage_core/src/functions/linear_algebra.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use permutohedron::heap_recursive;
use savage_macros::function;

use crate::{expression::Expression, functions::SquareMatrix, helpers::*};

#[function(
    name = "det",
    description = "determinant of a square matrix",
    examples = r#"[
        ("det([[1, 2], [3, 4]])", "-2"),
        ("det([[a, b], [c, d]])", "a * d - b * c"),
        ("det([])", "1"),
    ]"#,
    categories = r#"[
        "linear algebra",
    ]"#
)]
fn determinant(matrix: SquareMatrix) -> Expression {
    if matrix.is_empty() {
        return int(1);
    }

    let mut indices = (0..matrix.nrows()).collect::<Vec<usize>>();

    let mut products = Vec::new();

    heap_recursive(indices.as_mut_slice(), |permutation| {
        products.push(
            (0..matrix.nrows())
                .map(|i| matrix[(i, permutation[i])].clone())
                .reduce(|a, b| a * b)
                .unwrap(),
        );
    });

    // The first permutation generated by Heap's algorithm is the identity,
    // which has positive sign...
    let mut positive = true;

    products
        .into_iter()
        .reduce(|a, b| {
            // ... and every following permutation differs from its predecessor
            // by exactly one transposition, which flips the sign.
            positive = !positive;

            if positive {
                a + b
            } else {
                a - b
            }
        })
        .unwrap()
}


================================================
FILE: savage_core/src/functions/logic.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use savage_macros::function;

#[function(
    name = "and",
    description = "logical conjunction",
    examples = r#"[
        ("and(true, true)", "true"),
        ("and(true, false)", "false"),
        ("and(false, true)", "false"),
        ("and(false, false)", "false"),
    ]"#,
    categories = r#"[
        "logic",
        "boolean operators",
    ]"#
)]
fn and(a: bool, b: bool) -> bool {
    a && b
}


================================================
FILE: savage_core/src/functions/mod.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

mod combinatorics;
mod linear_algebra;
mod logic;
mod number_theory;

use std::rc::Rc;

use num::Signed;
use savage_macros::functions;

use crate::expression::{Expression, Function as FunctionImplementation, Integer, Matrix};

/// Arbitrary-precision non-negative integer.
/// This type alias is intended for use in function signatures
/// to mark integer parameters that must be non-negative.
pub(crate) type NonNegativeInteger = Integer;

/// Arbitrary-precision positive integer.
/// This type alias is intended for use in function signatures
/// to mark integer parameters that must be positive.
pub(crate) type PositiveInteger = Integer;

/// Column-major square matrix with expressions as components.
/// This type alias is intended for use in function signatures
/// to mark matrix parameters that must be square matrices.
pub(crate) type SquareMatrix = Matrix;

/// Function parameter.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum Parameter {
    /// Any symbolic expression.
    Expression,
    /// Integer expression, or an expression that can be interpreted as an integer.
    Integer,
    /// Non-negative integer expression, or an expression that can be interpreted as a non-negative integer.
    NonNegativeInteger,
    /// Positive integer expression, or an expression that can be interpreted as a positive integer.
    PositiveInteger,
    /// Rational number expression, or an expression that can be interpreted as a rational number.
    Rational,
    /// Complex number expression, or an expression that can be interpreted as a complex number.
    Complex,
    /// Vector expression, or an expression that can be interpreted as a vector.
    Vector,
    /// Matrix expression, or an expression that can be interpreted as a matrix.
    Matrix,
    /// Matrix expression containing a square matrix, or an expression that can be interpreted as a square matrix.
    SquareMatrix,
    /// Boolean expression, or an expression that can be interpreted as a boolean value.
    Boolean,
}

/// Metadata associated with a function.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Metadata {
    /// Name used to represent the function (also, default identifier for invoking the function).
    pub name: &'static str,
    /// Human-readable description of the function.
    pub description: &'static str,
    /// Parameters expected by the function, in the expected order.
    pub parameters: &'static [Parameter],
    /// Usage examples for the function, as pairs of REPL input and output.
    pub examples: &'static [(&'static str, &'static str)],
    /// Categories associated with the function.
    pub categories: &'static [&'static str],
}

/// Function definition.
pub struct Function {
    /// Metadata associated with the function.
    pub metadata: Metadata,
    /// Implementation of the function.
    pub implementation: Rc<FunctionImplementation>,
}

/// Returns a regular function implementation that type-checks its arguments
/// based on the given `parameters` and then invokes the given function `proxy`.
fn wrap_proxy(
    parameters: &'static [Parameter],
    proxy: impl Fn(&[Expression]) -> Result<Expression, Expression> + 'static,
) -> Rc<FunctionImplementation> {
    use crate::evaluate::Error::*;
    use crate::expression::Type::{Arithmetic, Boolean as Bool, Unknown};
    use Parameter::*;

    Rc::new(move |expression, arguments, _| {
        if arguments.len() != parameters.len() {
            return Err(InvalidNumberOfArguments {
                expression: expression.clone(),
                min_number: parameters.len(),
                max_number: parameters.len(),
                given_number: arguments.len(),
            });
        }

        for (argument, parameter) in arguments.iter().zip(parameters) {
            if let Bool(None) | Arithmetic | Unknown = argument.typ() {
                if *parameter != Expression {
                    return Ok(expression.clone());
                }
            }

            let mut argument_valid = true;

            match parameter {
                NonNegativeInteger => {
                    if let Ok(integer) = crate::expression::Integer::try_from(argument.clone()) {
                        argument_valid = !integer.is_negative();
                    }
                }
                PositiveInteger => {
                    if let Ok(integer) = crate::expression::Integer::try_from(argument.clone()) {
                        argument_valid = integer.is_positive();
                    }
                }
                SquareMatrix => {
                    if let Ok(matrix) = crate::expression::Matrix::try_from(argument.clone()) {
                        argument_valid = matrix.is_square() || matrix.is_empty();
                    }
                }
                _ => (),
            }

            if !argument_valid {
                return Err(InvalidArgument {
                    expression: expression.clone(),
                    argument: argument.clone(),
                });
            }
        }

        proxy(arguments).map_err(|argument| InvalidArgument {
            expression: expression.clone(),
            argument,
        })
    })
}

/// Returns all available functions.
pub fn functions() -> Vec<Function> {
    functions!(
        logic::and,
        combinatorics::factorial,
        linear_algebra::determinant,
        number_theory::is_prime,
        number_theory::nth_prime,
        number_theory::prime_pi,
    )
}

/// Returns an expression representing the function with the given name,
/// or `None` if the function library contains no function with that name.
pub fn function_expression(name: &str) -> Option<Expression> {
    for function in functions() {
        if function.metadata.name == name {
            return Some(Expression::Function(
                function.metadata.name.to_owned(),
                function.implementation,
            ));
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use crate::evaluate::default_context;
    use crate::expression::Expression;
    use crate::functions::functions;

    #[track_caller]
    fn t(expression: &str, result: &str) {
        assert_eq!(
            expression
                .parse::<Expression>()
                .unwrap()
                .evaluate(&default_context())
                .unwrap()
                .to_string(),
            result,
        );
    }

    #[test]
    fn examples() {
        for function in functions() {
            for (expression, result) in function.metadata.examples {
                t(expression, result);
            }
        }
    }
}


================================================
FILE: savage_core/src/functions/number_theory.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use num::ToPrimitive;
use primal::StreamingSieve;
use savage_macros::function;

use crate::{
    expression::Expression,
    functions::{function_expression, NonNegativeInteger, PositiveInteger},
    helpers::*,
};

#[function(
    name = "is_prime",
    description = "whether the given non-negative integer is a prime number",
    examples = r#"[
        ("is_prime(0)", "false"),
        ("is_prime(1)", "false"),
        ("is_prime(2)", "true"),
        ("is_prime(29)", "true"),
        ("is_prime(2^31)", "false"),
        ("is_prime(2^31 - 1)", "true"),
    ]"#,
    categories = r#"[
        "number theory",
        "prime numbers",
    ]"#
)]
fn is_prime(n: NonNegativeInteger) -> Expression {
    if let Some(n) = n.to_u64() {
        Expression::Boolean(primal::is_prime(n))
    } else {
        fun(function_expression("is_prime").unwrap(), [int(n)])
    }
}

#[function(
    name = "nth_prime",
    description = "`n`th prime number, 1-indexed",
    examples = r#"[
        ("nth_prime(1)", "2"),
        ("nth_prime(10)", "29"),
        ("nth_prime(100)", "541"),
        ("nth_prime(1000)", "7919"),
    ]"#,
    categories = r#"[
        "number theory",
        "prime numbers",
    ]"#
)]
fn nth_prime(n: PositiveInteger) -> Expression {
    if let Some(n) = n.to_usize() {
        int(StreamingSieve::nth_prime(n))
    } else {
        fun(function_expression("nth_prime").unwrap(), [int(n)])
    }
}

#[function(
    name = "prime_pi",
    description = "number of prime numbers less than or equal to the given non-negative integer",
    examples = r#"[
        ("prime_pi(10)", "4"),
        ("prime_pi(100)", "25"),
        ("prime_pi(1000)", "168"),
        ("prime_pi(10000)", "1229"),
        ("prime_pi(100000)", "9592"),
    ]"#,
    categories = r#"[
        "number theory",
        "prime numbers",
    ]"#
)]
fn prime_pi(n: NonNegativeInteger) -> Expression {
    if let Some(n) = n.to_usize() {
        int(StreamingSieve::prime_pi(n))
    } else {
        fun(function_expression("prime_pi").unwrap(), [int(n)])
    }
}


================================================
FILE: savage_core/src/helpers.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

//! Operators, conversions, and helper functions to make working with expressions easier.

use std::ops::{
    Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign,
};

use num::{One, Zero};

use crate::expression::{
    Complex, Expression, Integer, Matrix, Rational, RationalRepresentation, Type, Vector,
};

impl Neg for Expression {
    type Output = Self;

    fn neg(self) -> Self {
        Expression::Negation(Box::new(self))
    }
}

impl Not for Expression {
    type Output = Self;

    fn not(self) -> Self {
        Expression::Not(Box::new(self))
    }
}

impl Add for Expression {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Expression::Sum(Box::new(self), Box::new(other))
    }
}

impl AddAssign for Expression {
    fn add_assign(&mut self, other: Self) {
        *self = self.clone() + other;
    }
}

impl Sub for Expression {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Expression::Difference(Box::new(self), Box::new(other))
    }
}

impl SubAssign for Expression {
    fn sub_assign(&mut self, other: Self) {
        *self = self.clone() - other;
    }
}

impl Mul for Expression {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        Expression::Product(Box::new(self), Box::new(other))
    }
}

impl MulAssign for Expression {
    fn mul_assign(&mut self, other: Self) {
        *self = self.clone() * other;
    }
}

impl Div for Expression {
    type Output = Self;

    fn div(self, other: Self) -> Self {
        Expression::Quotient(Box::new(self), Box::new(other))
    }
}

impl DivAssign for Expression {
    fn div_assign(&mut self, other: Self) {
        *self = self.clone() / other;
    }
}

impl Rem for Expression {
    type Output = Self;

    fn rem(self, other: Self) -> Self {
        Expression::Remainder(Box::new(self), Box::new(other))
    }
}

impl RemAssign for Expression {
    fn rem_assign(&mut self, other: Self) {
        *self = self.clone() % other;
    }
}

impl From<&Self> for Expression {
    fn from(expression: &Self) -> Self {
        expression.clone()
    }
}

impl From<Integer> for Expression {
    fn from(integer: Integer) -> Self {
        Expression::Integer(integer)
    }
}

impl TryFrom<Expression> for Integer {
    type Error = Expression;

    fn try_from(expression: Expression) -> Result<Self, Self::Error> {
        if let Type::Number(z, _) = expression.typ() {
            if z.im.is_zero() && z.re.denom().is_one() {
                Ok(z.re.numer().clone())
            } else {
                Err(expression)
            }
        } else {
            Err(expression)
        }
    }
}

impl From<Rational> for Expression {
    fn from(rational: Rational) -> Self {
        Expression::Rational(rational, RationalRepresentation::Fraction)
    }
}

impl TryFrom<Expression> for Rational {
    type Error = Expression;

    fn try_from(expression: Expression) -> Result<Self, Self::Error> {
        if let Type::Number(z, _) = expression.typ() {
            if z.im.is_zero() {
                Ok(z.re)
            } else {
                Err(expression)
            }
        } else {
            Err(expression)
        }
    }
}

impl From<Complex> for Expression {
    fn from(complex: Complex) -> Self {
        Expression::Complex(complex, RationalRepresentation::Fraction)
    }
}

impl TryFrom<Expression> for Complex {
    type Error = Expression;

    fn try_from(expression: Expression) -> Result<Self, Self::Error> {
        if let Type::Number(z, _) = expression.typ() {
            Ok(z)
        } else {
            Err(expression)
        }
    }
}

impl From<Vector> for Expression {
    fn from(vector: Vector) -> Self {
        Expression::Vector(vector)
    }
}

impl TryFrom<Expression> for Vector {
    type Error = Expression;

    fn try_from(expression: Expression) -> Result<Self, Self::Error> {
        if let Type::Matrix(m) = expression.typ() {
            if m.ncols() == 1 {
                Ok(m.column(0).clone_owned())
            } else {
                Err(expression)
            }
        } else {
            Err(expression)
        }
    }
}

impl From<Matrix> for Expression {
    fn from(matrix: Matrix) -> Self {
        Expression::Matrix(matrix)
    }
}

impl TryFrom<Expression> for Matrix {
    type Error = Expression;

    fn try_from(expression: Expression) -> Result<Self, Self::Error> {
        if let Type::Matrix(m) = expression.typ() {
            Ok(m)
        } else {
            Err(expression)
        }
    }
}

impl From<bool> for Expression {
    fn from(boolean: bool) -> Self {
        Expression::Boolean(boolean)
    }
}

impl TryFrom<Expression> for bool {
    type Error = Expression;

    fn try_from(expression: Expression) -> Result<Self, Self::Error> {
        if let Expression::Boolean(boolean) = expression {
            Ok(boolean)
        } else {
            Err(expression)
        }
    }
}

/// Returns an expression representing the variable with the given identifier.
pub fn var(identifier: impl Into<String>) -> Expression {
    Expression::Variable(identifier.into())
}

/// Returns an expression representing the value of the given function at the given arguments.
pub fn fun(function: impl Into<Expression>, arguments: impl Into<Vec<Expression>>) -> Expression {
    Expression::FunctionValue(Box::new(function.into()), arguments.into())
}

/// Returns an expression representing the given integer.
pub fn int(integer: impl Into<Integer>) -> Expression {
    Expression::Integer(integer.into())
}

/// Returns an expression representing the rational number with
/// the given numerator and denominator, using fraction representation.
pub fn rat(numerator: impl Into<Integer>, denominator: impl Into<Integer>) -> Expression {
    Expression::Rational(
        Rational::new(numerator.into(), denominator.into()),
        RationalRepresentation::Fraction,
    )
}

/// Returns an expression representing the rational number with
/// the given numerator and denominator, using decimal representation,
/// falling back to fraction representation if the number cannot be
/// represented as a finite decimal.
pub fn ratd(numerator: impl Into<Integer>, denominator: impl Into<Integer>) -> Expression {
    Expression::Rational(
        Rational::new(numerator.into(), denominator.into()),
        RationalRepresentation::Decimal,
    )
}

/// Returns an expression representing the complex number with
/// real and imaginary parts being rational numbers described by
/// the given numerators and denominators, using fraction representation.
pub fn com(
    real_numerator: impl Into<Integer>,
    real_denominator: impl Into<Integer>,
    imaginary_numerator: impl Into<Integer>,
    imaginary_denominator: impl Into<Integer>,
) -> Expression {
    Expression::Complex(
        Complex::new(
            Rational::new(real_numerator.into(), real_denominator.into()),
            Rational::new(imaginary_numerator.into(), imaginary_denominator.into()),
        ),
        RationalRepresentation::Fraction,
    )
}

/// Returns an expression representing the complex number with
/// real and imaginary parts being rational numbers described by
/// the given numerators and denominators, using decimal representation,
/// falling back to fraction representation for parts that cannot be
/// represented as a finite decimal.
pub fn comd(
    real_numerator: impl Into<Integer>,
    real_denominator: impl Into<Integer>,
    imaginary_numerator: impl Into<Integer>,
    imaginary_denominator: impl Into<Integer>,
) -> Expression {
    Expression::Complex(
        Complex::new(
            Rational::new(real_numerator.into(), real_denominator.into()),
            Rational::new(imaginary_numerator.into(), imaginary_denominator.into()),
        ),
        RationalRepresentation::Decimal,
    )
}

/// Returns an expression representing the first expression raised to the power of the second.
pub fn pow(base: impl Into<Expression>, exponent: impl Into<Expression>) -> Expression {
    Expression::Power(Box::new(base.into()), Box::new(exponent.into()))
}

/// Returns an expression representing whether two expressions are equal.
pub fn eq(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {
    Expression::Equal(Box::new(left.into()), Box::new(right.into()))
}

/// Returns an expression representing whether two expressions are not equal.
pub fn ne(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {
    Expression::NotEqual(Box::new(left.into()), Box::new(right.into()))
}

/// Returns an expression representing whether the first expression is less than the second.
pub fn lt(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {
    Expression::LessThan(Box::new(left.into()), Box::new(right.into()))
}

/// Returns an expression representing whether the first expression is less than or equal to the second.
pub fn le(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {
    Expression::LessThanOrEqual(Box::new(left.into()), Box::new(right.into()))
}

/// Returns an expression representing whether the first expression is greater than the second.
pub fn gt(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {
    Expression::GreaterThan(Box::new(left.into()), Box::new(right.into()))
}

/// Returns an expression representing whether the first expression is greater than or equal to the second.
pub fn ge(left: impl Into<Expression>, right: impl Into<Expression>) -> Expression {
    Expression::GreaterThanOrEqual(Box::new(left.into()), Box::new(right.into()))
}

/// Returns an expression representing the logical conjunction (AND) of two expressions.
pub fn and(a: impl Into<Expression>, b: impl Into<Expression>) -> Expression {
    Expression::And(Box::new(a.into()), Box::new(b.into()))
}

/// Returns an expression representing the logical disjunction (OR) of two expressions.
pub fn or(a: impl Into<Expression>, b: impl Into<Expression>) -> Expression {
    Expression::Or(Box::new(a.into()), Box::new(b.into()))
}


================================================
FILE: savage_core/src/lib.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

pub mod evaluate;
pub mod expression;
pub mod functions;
pub mod helpers;
pub mod parse;
mod print;
mod simplify;


================================================
FILE: savage_core/src/parse.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use std::{ops::Range, str::FromStr};

use chumsky::prelude::*;

use crate::{
    expression::{Expression, Integer, Matrix, Vector},
    helpers::*,
};

/// Error that occurred while trying to parse a character stream into an expression.
pub type Error = chumsky::error::Simple<char, Range<usize>>;

/// Reason why a parse error occurred.
pub type ErrorReason = chumsky::error::SimpleReason<char, Range<usize>>;

/// Returns a parser that produces expressions from character streams.
///
/// The purpose of this function is to be a building block for parsers that parse
/// expressions as parts of a more complex input language. If you simply want
/// to turn strings into expressions, use `"a + b".parse::<Expression>()`.
#[allow(clippy::let_and_return)]
pub fn parser() -> impl Parser<char, Expression, Error = Error> {
    recursive(|expression| {
        let identifier = text::ident()
            .map(|identifier: String| match identifier.as_str() {
                "true" => Expression::Boolean(true),
                "false" => Expression::Boolean(false),
                _ => var(identifier),
            })
            .labelled("identifier")
            .boxed();

        let number = text::int(10)
            .chain(just('.').ignore_then(text::digits(10)).or_not())
            .map(|parts: Vec<String>| match parts.as_slice() {
                [integer] => int(integer.parse::<Integer>().unwrap()),
                [integer_part, fractional_part] => {
                    let numerator = format!("{}{}", integer_part, fractional_part);
                    let denominator = format!("1{}", "0".repeat(fractional_part.len()));
                    ratd(
                        numerator.parse::<Integer>().unwrap(),
                        denominator.parse::<Integer>().unwrap(),
                    )
                }
                _ => unreachable!(),
            })
            .labelled("number")
            .boxed();

        let vector_or_matrix = expression
            .clone()
            .separated_by(just(','))
            .padded()
            .delimited_by(just('['), just(']'))
            .map(|elements| {
                if let Some(Expression::Vector(v)) = elements.first() {
                    // If all elements of the vector are themselves vectors, and have the same size,
                    // they are interpreted as the rows of a rectangular matrix.
                    let row_size = v.len();
                    let mut rows = Vec::new();

                    for element in &elements {
                        match element {
                            Expression::Vector(v) if v.len() == row_size => {
                                rows.push(v.transpose());
                            }
                            _ => return Expression::Vector(Vector::from_vec(elements)),
                        }
                    }

                    Expression::Matrix(Matrix::from_rows(&rows))
                } else {
                    Expression::Vector(Vector::from_vec(elements))
                }
            })
            .labelled("vector_or_matrix")
            .boxed();

        let atomic_expression = identifier
            .or(number)
            .or(vector_or_matrix)
            .or(expression.clone().delimited_by(just('('), just(')')))
            .padded()
            .boxed();

        let function_or_element = atomic_expression
            .then(
                expression
                    .clone()
                    .separated_by(just(','))
                    .padded()
                    .delimited_by(just('('), just(')'))
                    .map(|arguments| (Some(arguments), None))
                    .or(expression
                        .clone()
                        .separated_by(just(','))
                        .at_least(1)
                        .at_most(2)
                        .delimited_by(just('['), just(']'))
                        .map(|indices| (None, Some(indices))))
                    .or_not(),
            )
            .map(
                |(expression, arguments_or_indices)| match arguments_or_indices {
                    Some((Some(arguments), None)) => fun(expression, arguments),
                    Some((None, Some(indices))) => {
                        if indices.len() == 1 {
                            Expression::VectorElement(
                                Box::new(expression),
                                Box::new(indices[0].clone()),
                            )
                        } else {
                            Expression::MatrixElement(
                                Box::new(expression),
                                Box::new(indices[0].clone()),
                                Box::new(indices[1].clone()),
                            )
                        }
                    }
                    None => expression,
                    _ => unreachable!(),
                },
            )
            .padded()
            .boxed();

        let power = function_or_element
            .separated_by(just('^'))
            .at_least(1)
            .map(|expressions| {
                expressions
                    .into_iter()
                    .rev()
                    .reduce(|a, b| pow(b, a))
                    .unwrap()
            })
            .labelled("power")
            .boxed();

        let negation = just('-')
            .ignore_then(power.clone())
            .map(|a| -a)
            .or(just('!').ignore_then(power.clone()).map(|a| !a))
            .labelled("negation")
            .or(power)
            .padded()
            .boxed();

        let product_or_quotient_or_remainder = negation
            .clone()
            .then(
                just('*')
                    .or(just('/'))
                    .or(just('%'))
                    .then(negation)
                    .repeated(),
            )
            .foldl(|a, (operator, b)| match operator {
                '*' => a * b,
                '/' => a / b,
                '%' => a % b,
                _ => unreachable!(),
            })
            .labelled("product_or_quotient_or_remainder")
            .boxed();

        let sum_or_difference = product_or_quotient_or_remainder
            .clone()
            .then(
                just('+')
                    .or(just('-'))
                    .then(product_or_quotient_or_remainder)
                    .repeated(),
            )
            .foldl(|a, (operator, b)| match operator {
                '+' => a + b,
                '-' => a - b,
                _ => unreachable!(),
            })
            .labelled("sum_or_difference")
            .boxed();

        let comparison = sum_or_difference
            .clone()
            .then(
                just('=')
                    .chain(just('='))
                    .or(just('!').chain(just('=')))
                    .or(just('<').chain(just('=')))
                    .or(just('<').to(vec!['<']))
                    .or(just('>').chain(just('=')))
                    .or(just('>').to(vec!['>']))
                    .collect::<String>()
                    .then(sum_or_difference)
                    .repeated(),
            )
            .foldl(|a, (operator, b)| match operator.as_str() {
                "==" => eq(a, b),
                "!=" => ne(a, b),
                "<" => lt(a, b),
                "<=" => le(a, b),
                ">" => gt(a, b),
                ">=" => ge(a, b),
                _ => unreachable!(),
            })
            .labelled("comparison")
            .boxed();

        let conjunction = comparison
            .clone()
            .then(
                just('&')
                    .ignore_then(just('&'))
                    .ignore_then(comparison)
                    .repeated(),
            )
            .foldl(and)
            .labelled("conjunction")
            .boxed();

        let disjunction = conjunction
            .clone()
            .then(
                just('|')
                    .ignore_then(just('|'))
                    .ignore_then(conjunction)
                    .repeated(),
            )
            .foldl(or)
            .labelled("disjunction")
            .boxed();

        disjunction
    })
}

impl FromStr for Expression {
    type Err = Vec<Error>;

    fn from_str(string: &str) -> Result<Self, Self::Err> {
        parser().then_ignore(end()).parse(string)
    }
}

#[cfg(test)]
mod tests {
    use nalgebra::{dmatrix, dvector};

    use crate::expression::{Expression, Expression::*};
    use crate::helpers::*;

    #[track_caller]
    fn t(string: &str, expression: Expression) {
        assert_eq!(string.parse(), Ok(expression));
    }

    #[test]
    fn variables() {
        t("a   ", var("a"));
        t("     A", var("A"));
        t("  Named_Variable ", var("Named_Variable"));
    }

    #[test]
    fn functions() {
        t(" f(   )   ", fun(var("f"), []));
        t("f ( a) ", fun(var("f"), [var("a")]));
        t("f( a, 1  )", fun(var("f"), [var("a"), int(1)]));
        t(
            " f(  g(a ),h(   b )  ) ",
            fun(
                var("f"),
                [fun(var("g"), [var("a")]), fun(var("h"), [var("b")])],
            ),
        );
        t(
            " ( f ( a ) ) ( b ) ",
            fun(fun(var("f"), [var("a")]), [var("b")]),
        );
        t("(f +g)( a)", fun(var("f") + var("g"), [var("a")]));
    }

    #[test]
    fn integers() {
        t("0", int(0));
        t("  1", int(1));
        t("1234567890  ", int(1234567890));
        t("  9876543210  ", int(9876543210u64));
    }

    #[test]
    fn rational_numbers() {
        t("0.5", ratd(1, 2));
        t(" 1.5", ratd(3, 2));
        t("3.075 ", ratd(123, 40));
        t(" 100.000 ", ratd(100, 1));
    }

    #[test]
    fn vectors() {
        t(" [ ] ", Vector(dvector![]));
        t("[   1]", Vector(dvector![int(1)]));
        t(" [1,2,   3 ]", Vector(dvector![int(1), int(2), int(3)]));
        t(
            "[  1,f(a,1),[   1,2,3  ] ]  ",
            Vector(dvector![
                int(1),
                fun(var("f"), [var("a"), int(1)]),
                Vector(dvector![int(1), int(2), int(3)])
            ]),
        );
    }

    #[test]
    fn matrices() {
        t("[[1   ]   ]   ", Matrix(dmatrix![int(1)]));
        t("[ [ 1,2,3 ] ]", Matrix(dmatrix![int(1), int(2), int(3)]));
        t(
            " [[  1, 2,3 ],[ 4,5, 6]]",
            Matrix(dmatrix![
                int(1), int(2), int(3);
                int(4), int(5), int(6)
            ]),
        );
        t(
            "  [[f ( ) ,2, [1 ] ], [[ [ 1]],3.075,6] ] ",
            Matrix(dmatrix![
                fun(var("f"), []), int(2), Vector(dvector![int(1)]);
                Matrix(dmatrix![int(1)]), ratd(123, 40), int(6)
            ]),
        );
    }

    #[test]
    fn booleans() {
        t("   true", Boolean(true));
        t("false   ", Boolean(false));
    }

    #[test]
    fn operators() {
        t("  - 1 ", -int(1));
        t(" - (-    1 )", -(-int(1)));
        t("!A  ", !var("A"));
        t(" !( ! A)", !(!var("A")));

        t("1+2    +3   ", (int(1) + int(2)) + int(3));
        t(" 1 +2- 3 ", (int(1) + int(2)) - int(3));
        t("1  -2 +    3", (int(1) - int(2)) + int(3));
        t("1-2-3", (int(1) - int(2)) - int(3));
        t(" 1-(2 + 3)", int(1) - (int(2) + int(3)));
        t("1 - (2 - 3)", int(1) - (int(2) - int(3)));

        t(" 1 *2* 3 ", (int(1) * int(2)) * int(3));
        t("1*2 / 3", (int(1) * int(2)) / int(3));
        t("1 / 2*3  ", (int(1) / int(2)) * int(3));
        t("  1/2/3", (int(1) / int(2)) / int(3));
        t("1 /(  2 *3) ", int(1) / (int(2) * int(3)));
        t(" 1/ (2 /3)", int(1) / (int(2) / int(3)));

        t("(1+2)   /3 ", (int(1) + int(2)) / int(3));
        t("  1/ 2 +3", (int(1) / int(2)) + int(3));
        t("1 + 2 / 3", int(1) + (int(2) / int(3)));
        t("1/ (2+3)     ", int(1) / (int(2) + int(3)));

        t("(1 * 2)^3", pow(int(1) * int(2), int(3)));
        t("1^2 * 3 ", pow(int(1), int(2)) * int(3));
        t("1*  2  ^3", int(1) * pow(int(2), int(3)));
        t(" 1^( 2 * 3 )", pow(int(1), int(2) * int(3)));

        t(" (1^2)  ^  3", pow(pow(int(1), int(2)), int(3)));
        t("1 ^2 ^3 ", pow(int(1), pow(int(2), int(3))));

        // TODO: Comparison operators!

        t("A&&B&&C", and(and(var("A"), var("B")), var("C")));
        t("A  &&  B||C", or(and(var("A"), var("B")), var("C")));
        t(" ( A || B ) && C ", and(or(var("A"), var("B")), var("C")));
        t("A||B ||C", or(or(var("A"), var("B")), var("C")));
        t("A&& ( B|| C)", and(var("A"), or(var("B"), var("C"))));
        t("   A|| B &&C", or(var("A"), and(var("B"), var("C"))));
    }

    // TODO: Replace with a real benchmark once `#[bench]` is stable.
    #[test]
    fn benchmark() {
        for depth in 0..20 {
            t(
                &format!("{}a{}", "(".repeat(depth), ")".repeat(depth)),
                var("a"),
            );
        }
    }
}


================================================
FILE: savage_core/src/print.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use std::cmp::max;
use std::fmt::{Display, Formatter, Result};

use num::{One, Signed, Zero};

use crate::expression::{Expression, Integer, Rational};

/// Returns a pair of integers `(n, m)` such that `x = n / 10^m`,
/// or `None` if no such integers exist.
fn decimal_representation(x: &Rational) -> Option<(Integer, usize)> {
    // https://en.wikipedia.org/wiki/Decimal_representation#Finite_decimal_representations
    let mut denominator = x.denom().clone();

    let [power_of_2, power_of_5] = [2, 5].map(|n| {
        let mut power = 0;

        while (denominator.clone() % Integer::from(n)).is_zero() {
            denominator /= n;
            power += 1;
        }

        power
    });

    if denominator.is_one() {
        let multiplier = if power_of_2 < power_of_5 {
            Integer::from(2).pow(power_of_5 - power_of_2)
        } else {
            Integer::from(5).pow(power_of_2 - power_of_5)
        };

        Some((x.numer() * multiplier, max(power_of_2, power_of_5) as usize))
    } else {
        None
    }
}

impl Expression {
    /// Formats the expression as a unary prefix operator with the minimally necessary parentheses.
    fn fmt_prefix(&self, f: &mut Formatter<'_>, symbol: &str, a: &Self) -> Result {
        let a_needs_parentheses = a.precedence() <= self.precedence();

        write!(
            f,
            "{}{}{}{}",
            symbol,
            if a_needs_parentheses { "(" } else { "" },
            a,
            if a_needs_parentheses { ")" } else { "" },
        )
    }

    /// Formats the expression as a binary infix operator with the minimally necessary parentheses.
    fn fmt_infix(&self, f: &mut Formatter<'_>, symbol: &str, a: &Self, b: &Self) -> Result {
        use crate::expression::Associativity::*;

        let a_needs_parentheses = (a.precedence() < self.precedence())
            || ((a.precedence() == self.precedence())
                && (self.associativity() == RightAssociative));

        let b_needs_parentheses = (b.precedence() < self.precedence())
            || ((b.precedence() == self.precedence()) && (self.associativity() == LeftAssociative));

        write!(
            f,
            "{}{}{} {} {}{}{}",
            if a_needs_parentheses { "(" } else { "" },
            a,
            if a_needs_parentheses { ")" } else { "" },
            symbol,
            if b_needs_parentheses { "(" } else { "" },
            b,
            if b_needs_parentheses { ")" } else { "" },
        )
    }
}

impl Display for Expression {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        use crate::expression::{Expression::*, RationalRepresentation::*};

        match self {
            Variable(identifier) => write!(f, "{}", identifier),
            Function(identifier, _) => write!(f, "{}", identifier),
            FunctionValue(function, arguments) => {
                let function_needs_parentheses = function.precedence() < isize::MAX;

                write!(
                    f,
                    "{}{}{}({})",
                    if function_needs_parentheses { "(" } else { "" },
                    function,
                    if function_needs_parentheses { ")" } else { "" },
                    arguments
                        .iter()
                        .map(|a| a.to_string())
                        .collect::<Vec<_>>()
                        .join(", "),
                )
            }
            Integer(n) => write!(f, "{}", n),
            Rational(x, representation) => {
                match representation {
                    Fraction => write!(f, "{}", x),
                    Decimal => {
                        if let Some((mantissa, separator_position)) = decimal_representation(x) {
                            let mut string = mantissa.abs().to_string();

                            if separator_position > 0 {
                                if separator_position > string.len() - 1 {
                                    // Left-pad the string with enough zeros to be able
                                    // to insert the decimal separator at the indicated position.
                                    string = format!(
                                        "{}{}",
                                        "0".repeat(separator_position - (string.len() - 1)),
                                        string,
                                    );
                                }

                                string.insert(string.len() - separator_position, '.');
                            }

                            write!(f, "{}{}", if x.is_negative() { "-" } else { "" }, string)
                        } else {
                            // Fall back to fraction representation.
                            write!(f, "{}", x)
                        }
                    }
                }
            }
            Complex(z, representation) => {
                if z.im.is_zero() {
                    write!(f, "{}", Rational(z.re.clone(), *representation))
                } else if z.re.is_zero() {
                    if z.im.abs().is_one() {
                        write!(f, "{}i", if z.im.is_negative() { "-" } else { "" })
                    } else {
                        write!(f, "{}*i", Rational(z.im.clone(), *representation))
                    }
                } else if z.re.is_negative() && z.im.is_positive() {
                    if z.im.is_one() {
                        write!(f, "i - {}", Rational(z.re.abs(), *representation))
                    } else {
                        write!(
                            f,
                            "{}*i - {}",
                            Rational(z.im.clone(), *representation),
                            Rational(z.re.abs(), *representation),
                        )
                    }
                } else if z.im.abs().is_one() {
                    write!(
                        f,
                        "{} {} i",
                        Rational(z.re.clone(), *representation),
                        if z.im.is_negative() { "-" } else { "+" },
                    )
                } else {
                    write!(
                        f,
                        "{} {} {}*i",
                        Rational(z.re.clone(), *representation),
                        if z.im.is_negative() { "-" } else { "+" },
                        Rational(z.im.abs(), *representation),
                    )
                }
            }
            Vector(v) => write!(
                f,
                "[{}]",
                v.iter()
                    .map(|element| element.to_string())
                    .collect::<Vec<_>>()
                    .join(", "),
            ),
            VectorElement(vector, i) => {
                let vector_needs_parentheses = vector.precedence() < isize::MAX;

                write!(
                    f,
                    "{}{}{}[{}]",
                    if vector_needs_parentheses { "(" } else { "" },
                    vector,
                    if vector_needs_parentheses { ")" } else { "" },
                    i,
                )
            }
            Matrix(m) => write!(
                f,
                "[{}]",
                m.row_iter()
                    .map(|row| format!(
                        "[{}]",
                        row.iter()
                            .map(|element| element.to_string())
                            .collect::<Vec<_>>()
                            .join(", "),
                    ))
                    .collect::<Vec<_>>()
                    .join(", "),
            ),
            MatrixElement(matrix, i, j) => {
                let matrix_needs_parentheses = matrix.precedence() < isize::MAX;

                write!(
                    f,
                    "{}{}{}[{}, {}]",
                    if matrix_needs_parentheses { "(" } else { "" },
                    matrix,
                    if matrix_needs_parentheses { ")" } else { "" },
                    i,
                    j,
                )
            }
            Boolean(boolean) => write!(f, "{}", boolean),
            Negation(a) => self.fmt_prefix(f, "-", a),
            Not(a) => self.fmt_prefix(f, "!", a),
            Sum(a, b) => self.fmt_infix(f, "+", a, b),
            Difference(a, b) => self.fmt_infix(f, "-", a, b),
            Product(a, b) => self.fmt_infix(f, "*", a, b),
            Quotient(a, b) => self.fmt_infix(f, "/", a, b),
            Remainder(a, b) => self.fmt_infix(f, "%", a, b),
            Power(a, b) => self.fmt_infix(f, "^", a, b),
            Equal(a, b) => self.fmt_infix(f, "==", a, b),
            NotEqual(a, b) => self.fmt_infix(f, "!=", a, b),
            LessThan(a, b) => self.fmt_infix(f, "<", a, b),
            LessThanOrEqual(a, b) => self.fmt_infix(f, "<=", a, b),
            GreaterThan(a, b) => self.fmt_infix(f, ">", a, b),
            GreaterThanOrEqual(a, b) => self.fmt_infix(f, ">=", a, b),
            And(a, b) => self.fmt_infix(f, "&&", a, b),
            Or(a, b) => self.fmt_infix(f, "||", a, b),
        }
    }
}

#[cfg(test)]
mod tests {
    use nalgebra::{dmatrix, dvector};

    use crate::expression::{Expression, Expression::*};
    use crate::helpers::*;

    #[track_caller]
    fn t(expression: Expression, string: &str) {
        assert_eq!(expression.to_string(), string);
    }

    #[test]
    fn variables() {
        t(var("a"), "a");
        t(var("A"), "A");
        t(var("Named_Variable"), "Named_Variable");
    }

    #[test]
    fn functions() {
        t(fun(var("f"), []), "f()");
        t(fun(var("f"), [var("a")]), "f(a)");
        t(fun(var("f"), [var("a"), int(1)]), "f(a, 1)");
        t(
            fun(
                var("f"),
                [fun(var("g"), [var("a")]), fun(var("h"), [var("b")])],
            ),
            "f(g(a), h(b))",
        );
        t(fun(fun(var("f"), [var("a")]), [var("b")]), "(f(a))(b)");
        t(fun(var("f") + var("g"), [var("a")]), "(f + g)(a)");
    }

    #[test]
    fn integers() {
        t(int(0), "0");
        t(int(1), "1");
        t(int(-1), "-1");
        t(int(1234567890), "1234567890");
        t(int(-1234567890), "-1234567890");
        t(int(9876543210u64), "9876543210");
        t(int(-9876543210i64), "-9876543210");
    }

    #[test]
    fn rational_numbers() {
        t(rat(0, 1), "0");
        t(ratd(0, 1), "0");
        t(rat(0, -1), "0");
        t(ratd(0, -1), "0");
        t(rat(1, 1), "1");
        t(ratd(1, 1), "1");
        t(rat(-1, 1), "-1");
        t(ratd(-1, 1), "-1");
        t(rat(1, 2), "1/2");
        t(ratd(1, 2), "0.5");
        t(rat(3, 2), "3/2");
        t(ratd(3, 2), "1.5");
        t(rat(1, 3), "1/3");
        t(ratd(1, 3), "1/3");
        t(rat(123, 40), "123/40");
        t(ratd(123, 40), "3.075");
        t(rat(123, -40), "-123/40");
        t(ratd(123, -40), "-3.075");
        t(rat(-123, -40), "123/40");
        t(ratd(-123, -40), "3.075");
    }

    #[test]
    fn complex_numbers() {
        t(com(0, 1, 0, 1), "0");
        t(comd(0, 1, 0, 1), "0");
        t(com(1, 1, 0, 1), "1");
        t(comd(1, 1, 0, 1), "1");
        t(com(0, 1, 1, 1), "i");
        t(comd(0, 1, 1, 1), "i");
        t(com(-1, 1, 0, 1), "-1");
        t(comd(-1, 1, 0, 1), "-1");
        t(com(0, 1, -1, 1), "-i");
        t(comd(0, 1, -1, 1), "-i");
        t(com(1, 1, 1, 1), "1 + i");
        t(comd(1, 1, 1, 1), "1 + i");
        t(com(1, 1, -1, 1), "1 - i");
        t(comd(1, 1, -1, 1), "1 - i");
        t(com(-1, 1, 1, 1), "i - 1");
        t(comd(-1, 1, 1, 1), "i - 1");
        t(com(-1, 1, -1, 1), "-1 - i");
        t(comd(-1, 1, -1, 1), "-1 - i");
        t(com(123, -40, 1, 3), "1/3*i - 123/40");
        t(comd(123, -40, 1, 3), "1/3*i - 3.075");
        t(com(1, 3, 123, 40), "1/3 + 123/40*i");
        t(comd(1, 3, 123, 40), "1/3 + 3.075*i");
    }

    #[test]
    fn vectors() {
        t(Vector(dvector![]), "[]");
        t(Vector(dvector![int(1)]), "[1]");
        t(Vector(dvector![int(1), int(2), int(3)]), "[1, 2, 3]");
        t(
            Vector(dvector![
                int(1),
                fun(var("f"), [var("a"), int(1)]),
                Vector(dvector![int(1), int(2), int(3)])
            ]),
            "[1, f(a, 1), [1, 2, 3]]",
        );
    }

    #[test]
    fn matrices() {
        t(Matrix(dmatrix![]), "[]");
        t(Matrix(dmatrix![int(1)]), "[[1]]");
        t(Matrix(dmatrix![int(1), int(2), int(3)]), "[[1, 2, 3]]");
        t(
            Matrix(dmatrix![
                int(1), int(2), int(3);
                int(4), int(5), int(6)
            ]),
            "[[1, 2, 3], [4, 5, 6]]",
        );
        t(
            Matrix(dmatrix![
                fun(var("f"), []), int(2), Vector(dvector![int(1)]);
                Matrix(dmatrix![int(1)]), comd(123, -40, 1, 3), int(6)
            ]),
            "[[f(), 2, [1]], [[[1]], 1/3*i - 3.075, 6]]",
        );
    }

    #[test]
    fn booleans() {
        t(Boolean(true), "true");
        t(Boolean(false), "false");
    }

    #[test]
    fn operators() {
        t(-int(1), "-1");
        t(-(-int(1)), "-(-1)");
        t(!var("A"), "!A");
        t(!(!var("A")), "!(!A)");

        t((int(1) + int(2)) + int(3), "1 + 2 + 3");
        t((int(1) + int(2)) - int(3), "1 + 2 - 3");
        t((int(1) - int(2)) + int(3), "1 - 2 + 3");
        t((int(1) - int(2)) - int(3), "1 - 2 - 3");
        t(int(1) + (int(2) + int(3)), "1 + 2 + 3");
        t(int(1) + (int(2) - int(3)), "1 + 2 - 3");
        t(int(1) - (int(2) + int(3)), "1 - (2 + 3)");
        t(int(1) - (int(2) - int(3)), "1 - (2 - 3)");

        t((int(1) * int(2)) * int(3), "1 * 2 * 3");
        t((int(1) * int(2)) / int(3), "1 * 2 / 3");
        t((int(1) / int(2)) * int(3), "1 / 2 * 3");
        t((int(1) / int(2)) / int(3), "1 / 2 / 3");
        t(int(1) * (int(2) * int(3)), "1 * 2 * 3");
        t(int(1) * (int(2) / int(3)), "1 * 2 / 3");
        t(int(1) / (int(2) * int(3)), "1 / (2 * 3)");
        t(int(1) / (int(2) / int(3)), "1 / (2 / 3)");

        t((int(1) + int(2)) / int(3), "(1 + 2) / 3");
        t((int(1) / int(2)) + int(3), "1 / 2 + 3");
        t(int(1) + (int(2) / int(3)), "1 + 2 / 3");
        t(int(1) / (int(2) + int(3)), "1 / (2 + 3)");

        t(pow(int(1) * int(2), int(3)), "(1 * 2) ^ 3");
        t(pow(int(1), int(2)) * int(3), "1 ^ 2 * 3");
        t(int(1) * pow(int(2), int(3)), "1 * 2 ^ 3");
        t(pow(int(1), int(2) * int(3)), "1 ^ (2 * 3)");

        t(pow(pow(int(1), int(2)), int(3)), "(1 ^ 2) ^ 3");
        t(pow(int(1), pow(int(2), int(3))), "1 ^ 2 ^ 3");

        t(pow(int(1), int(2)), "1 ^ 2");
        t(pow(int(-1), int(2)), "(-1) ^ 2");
        t(pow(rat(1, 2), int(3)), "(1/2) ^ 3");
        t(pow(ratd(1, 2), int(3)), "0.5 ^ 3");
        t(pow(com(0, 1, -1, 1), int(2)), "(-i) ^ 2");
        t(com(1, 1, 1, 1) * int(2), "(1 + i) * 2");
        t(com(1, 1, -1, 1) - int(2), "1 - i - 2");
        t(int(2) - com(1, 1, -1, 1), "2 - (1 - i)");

        // TODO: Comparison operators!

        t(and(and(var("A"), var("B")), var("C")), "A && B && C");
        t(or(and(var("A"), var("B")), var("C")), "A && B || C");
        t(and(or(var("A"), var("B")), var("C")), "(A || B) && C");
        t(or(or(var("A"), var("B")), var("C")), "A || B || C");
        t(and(var("A"), and(var("B"), var("C"))), "A && B && C");
        t(and(var("A"), or(var("B"), var("C"))), "A && (B || C)");
        t(or(var("A"), and(var("B"), var("C"))), "A || B && C");
        t(or(var("A"), or(var("B"), var("C"))), "A || B || C");
    }
}


================================================
FILE: savage_core/src/simplify.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use crate::{expression::Expression, helpers::*};

impl Expression {
    /// Applies standard algebraic simplification rules to the expression,
    /// and returns the result.
    ///
    /// Note that this function does not itself recurse into sub-expressions;
    /// but since it is called from `evaluate_step`, which *does* recurse,
    /// simplifications are applied to the entire expression tree during evaluation.
    pub(crate) fn simplify(&self) -> Self {
        use crate::expression::Expression::*;

        match self {
            Negation(a) => {
                if let Negation(a) = &**a {
                    *a.clone()
                } else {
                    self.clone()
                }
            }
            Not(a) => {
                if let Not(a) = &**a {
                    *a.clone()
                } else {
                    self.clone()
                }
            }
            Sum(a, b) => {
                let a = *a.clone();
                let b = *b.clone();

                if a == int(0) {
                    b
                } else if b == int(0) {
                    a
                } else if a == b {
                    int(2) * a
                } else if a == -b.clone() || b == -a {
                    int(0)
                } else {
                    self.clone()
                }
            }
            Difference(a, b) => {
                let a = *a.clone();
                let b = *b.clone();

                if a == int(0) {
                    -b
                } else if b == int(0) {
                    a
                } else if a == b {
                    int(0)
                } else if a == -b.clone() || b == -a.clone() {
                    int(2) * a
                } else {
                    self.clone()
                }
            }
            Product(a, b) => {
                let a = *a.clone();
                let b = *b.clone();

                if a == int(1) {
                    b
                } else if b == int(1) {
                    a
                } else if a == int(0) || b == int(0) {
                    int(0)
                } else if a == b {
                    pow(a, int(2))
                } else if a == int(1) / b.clone() || b == int(1) / a {
                    int(1)
                } else {
                    self.clone()
                }
            }
            Quotient(a, b) => {
                let a = *a.clone();
                let b = *b.clone();

                if b == int(1) {
                    a
                } else if a == int(0) {
                    // FIXME: This is incorrect if `b` evaluates to zero!
                    int(0)
                } else if a == b {
                    // FIXME: This is incorrect if `b` evaluates to zero!
                    int(1)
                } else {
                    self.clone()
                }
            }
            Remainder(a, b) => {
                let a = *a.clone();
                let b = *b.clone();

                if a == int(0) || a == b {
                    // FIXME: This is incorrect if `b` evaluates to zero!
                    int(0)
                } else {
                    self.clone()
                }
            }
            Power(a, b) => {
                let a = *a.clone();
                let b = *b.clone();

                if a == int(1) {
                    int(1)
                } else if b == int(1) {
                    a
                } else if a == int(0) {
                    // FIXME: This is incorrect if `b` evaluates to zero!
                    int(0)
                } else if b == int(0) {
                    // FIXME: This is incorrect if `a` evaluates to zero!
                    int(1)
                } else {
                    self.clone()
                }
            }
            Equal(a, b) | LessThanOrEqual(a, b) | GreaterThanOrEqual(a, b) => {
                if a == b {
                    Boolean(true)
                } else {
                    self.clone()
                }
            }
            NotEqual(a, b) | LessThan(a, b) | GreaterThan(a, b) => {
                if a == b {
                    Boolean(false)
                } else {
                    self.clone()
                }
            }
            And(a, b) => {
                let a = *a.clone();
                let b = *b.clone();

                if a == Boolean(true) {
                    b
                } else if b == Boolean(true) {
                    a
                } else if a == Boolean(false) || b == Boolean(false) {
                    Boolean(false)
                } else if a == b {
                    a
                } else if a == !b.clone() || b == !a {
                    Boolean(false)
                } else {
                    self.clone()
                }
            }
            Or(a, b) => {
                let a = *a.clone();
                let b = *b.clone();

                if a == Boolean(false) {
                    b
                } else if b == Boolean(false) {
                    a
                } else if a == Boolean(true) || b == Boolean(true) {
                    Boolean(true)
                } else if a == b {
                    a
                } else if a == !b.clone() || b == !a {
                    Boolean(true)
                } else {
                    self.clone()
                }
            }
            _ => self.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::expression::Expression;

    #[track_caller]
    fn t(expression: &str, result: &str) {
        assert_eq!(
            expression
                .parse::<Expression>()
                .unwrap()
                .simplify()
                .to_string(),
            result,
        );
    }

    #[test]
    fn arithmetic() {
        t("-(-a)", "a");

        t("0 + a", "a");
        t("a + 0", "a");
        t("a + a", "2 * a");
        t("(-a) + a", "0");
        t("a + (-a)", "0");

        t("0 - a", "-a");
        t("a - 0", "a");
        t("a - a", "0");
        t("(-a) - a", "2 * -a");
        t("a - (-a)", "2 * a");

        t("1 * a", "a");
        t("a * 1", "a");
        t("0 * a", "0");
        t("a * 0", "0");
        t("a * a", "a ^ 2");
        t("(1 / a) * a", "1");
        t("a * (1 / a)", "1");

        t("a / 1", "a");
        t("0 / a", "0");
        t("a / a", "1");

        t("0 % a", "0");
        t("a % a", "0");

        t("1 ^ a", "1");
        t("a ^ 1", "a");
        t("0 ^ a", "0");
        t("a ^ 0", "1");
    }

    #[test]
    fn logic() {
        t("!(!a)", "a");

        t("true && a", "a");
        t("a && true", "a");
        t("false && a", "false");
        t("a && false", "false");
        t("a && a", "a");
        t("(!a) && a", "false");
        t("a && (!a)", "false");

        t("false || a", "a");
        t("a || false", "a");
        t("true || a", "true");
        t("a || true", "true");
        t("a || a", "a");
        t("(!a) || a", "true");
        t("a || (!a)", "true");
    }

    #[test]
    fn comparisons() {
        t("a == a", "true");
        t("a != a", "false");
        t("a < a", "false");
        t("a <= a", "true");
        t("a > a", "false");
        t("a >= a", "true");
    }
}


================================================
FILE: savage_macros/Cargo.toml
================================================
[package]
name = "savage_macros"
version = "0.1.0"
authors = ["Philipp Emanuel Weidmann <pew@worldwidemann.com>"]
description = "A primitive computer algebra system (macro helper crate, NOT INTENDED FOR USE BY THIRD-PARTY CRATES)"
repository = "https://github.com/p-e-w/savage"
readme = "README.md"
license = "AGPL-3.0-or-later"
edition = "2021"

[lib]
proc-macro = true

[dependencies]
syn = "1.0.85"
quote = "1.0.14"
darling = "0.14.1"


================================================
FILE: savage_macros/src/lib.rs
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.com>

use darling::FromMeta;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{
    parse_macro_input, punctuated::Punctuated, token::Comma, AttributeArgs, ExprArray, FnArg,
    ItemFn, Path, Type,
};

#[derive(FromMeta)]
struct Arguments {
    name: String,
    description: String,
    examples: ExprArray,
    categories: ExprArray,
}

/// Generates code required for the marked function to be usable in a function expression.
/// Function metadata is generated from the provided attribute arguments.
#[proc_macro_attribute]
pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
    let arguments = match Arguments::from_list(&parse_macro_input!(attr as AttributeArgs)) {
        Ok(arguments) => arguments,
        Err(error) => return TokenStream::from(error.write_errors()),
    };

    let name_argument = arguments.name;
    let description_argument = arguments.description;
    let examples_argument = arguments.examples;
    let categories_argument = arguments.categories;

    let item_fn = parse_macro_input!(item as ItemFn);

    let name = &item_fn.sig.ident;
    let metadata_name = format_ident!("{}_METADATA", name.to_string().to_uppercase());
    let proxy_name = format_ident!("{}_proxy", name);

    let parameters = item_fn.sig.inputs.iter().map(|fn_arg| {
        if let FnArg::Typed(pat_type) = fn_arg {
            if let Type::Path(type_path) = &*pat_type.ty {
                match type_path.path.get_ident().unwrap().to_string().as_str() {
                    "Expression" => quote! { crate::functions::Parameter::Expression },
                    "Integer" => quote! { crate::functions::Parameter::Integer },
                    "NonNegativeInteger" => {
                        quote! { crate::functions::Parameter::NonNegativeInteger }
                    }
                    "PositiveInteger" => {
                        quote! { crate::functions::Parameter::PositiveInteger }
                    }
                    "Rational" => quote! { crate::functions::Parameter::Rational },
                    "Complex" => quote! { crate::functions::Parameter::Complex },
                    "Vector" => quote! { crate::functions::Parameter::Vector },
                    "Matrix" => quote! { crate::functions::Parameter::Matrix },
                    "SquareMatrix" => quote! { crate::functions::Parameter::SquareMatrix },
                    "bool" => quote! { crate::functions::Parameter::Boolean },
                    _ => unimplemented!(),
                }
            } else {
                unreachable!();
            }
        } else {
            unreachable!();
        }
    });

    let arguments =
        (0..item_fn.sig.inputs.len()).map(|i| quote! { arguments[#i].clone().try_into()? });

    let tokens = quote! {
        #item_fn

        pub(crate) const #metadata_name: crate::functions::Metadata = crate::functions::Metadata {
            name: #name_argument,
            description: #description_argument,
            parameters: &[#(#parameters),*],
            examples: &#examples_argument,
            categories: &#categories_argument,
        };

        pub(crate) fn #proxy_name(arguments: &[crate::expression::Expression]) ->
            ::std::result::Result<crate::expression::Expression, crate::expression::Expression> {
            ::std::result::Result::Ok(#name(#(#arguments),*).into())
        }
    };

    tokens.into()
}

/// Returns a vector of function definitions generated from the base function paths provided as arguments.
#[proc_macro]
pub fn functions(input: TokenStream) -> TokenStream {
    let mut statements = Vec::new();

    for path in parse_macro_input!(input with Punctuated::<Path, Comma>::parse_terminated) {
        let name = &path.segments.last().unwrap().ident;

        let mut metadata_path = path.clone();
        metadata_path.segments.last_mut().unwrap().ident =
            format_ident!("{}_METADATA", name.to_string().to_uppercase());

        let mut proxy_path = path.clone();
        proxy_path.segments.last_mut().unwrap().ident = format_ident!("{}_proxy", name);

        statements.push(quote! {
            functions.push(Function {
                metadata: #metadata_path,
                implementation: wrap_proxy(#metadata_path.parameters, #proxy_path),
            });
        });
    }

    let tokens = quote! {{
        let mut functions = Vec::new();

        #(#statements)*

        functions
    }};

    tokens.into()
}
Download .txt
gitextract_86suw3hs/

├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       └── continuous_integration.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE
├── README.md
├── savage/
│   ├── Cargo.toml
│   ├── help/
│   │   ├── footer.md
│   │   └── header.md
│   └── src/
│       ├── command.rs
│       ├── help.rs
│       ├── input.rs
│       └── main.rs
├── savage_core/
│   ├── Cargo.toml
│   └── src/
│       ├── evaluate.rs
│       ├── expression.rs
│       ├── functions/
│       │   ├── combinatorics.rs
│       │   ├── linear_algebra.rs
│       │   ├── logic.rs
│       │   ├── mod.rs
│       │   └── number_theory.rs
│       ├── helpers.rs
│       ├── lib.rs
│       ├── parse.rs
│       ├── print.rs
│       └── simplify.rs
└── savage_macros/
    ├── Cargo.toml
    └── src/
        └── lib.rs
Download .txt
SYMBOL INDEX (156 symbols across 16 files)

FILE: savage/src/command.rs
  type Command (line 13) | pub enum Command {
  function parser (line 20) | fn parser() -> impl Parser<char, Command, Error = Error> {
  type Err (line 49) | type Err = Vec<Error>;
  method from_str (line 51) | fn from_str(string: &str) -> Result<Self, Self::Err> {
  function t (line 63) | fn t(string: &str, command: Command) {
  function parse (line 68) | fn parse() {

FILE: savage/src/help.rs
  constant HELP_HEADER (line 23) | const HELP_HEADER: &str = include_str!("../help/header.md");
  constant HELP_FOOTER (line 24) | const HELP_FOOTER: &str = include_str!("../help/footer.md");
  function view_area (line 76) | fn view_area() -> Area {
  function show_help (line 87) | pub fn show_help(text: String) -> Result<(), Error> {

FILE: savage/src/input.rs
  type TokenType (line 17) | enum TokenType {
  function tokenize (line 27) | fn tokenize(input: &str) -> Vec<(String, TokenType)> {
  type InputHelper (line 85) | pub struct InputHelper {}
  method highlight_prompt (line 88) | fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
  method highlight (line 96) | fn highlight<'l>(&self, line: &'l str, pos: usize) -> Cow<'l, str> {
  method highlight_char (line 165) | fn highlight_char(&self, _line: &str, _pos: usize) -> bool {
  method validate (line 171) | fn validate(&self, ctx: &mut ValidationContext) -> Result<ValidationResu...

FILE: savage/src/main.rs
  function format_parse_error (line 37) | fn format_parse_error(error: ParseError) -> Report {
  function main (line 97) | fn main() {

FILE: savage_core/src/evaluate.rs
  type Error (line 15) | pub enum Error {
  function default_context (line 64) | pub fn default_context() -> HashMap<String, Expression> {
  method evaluate_step_unary (line 87) | fn evaluate_step_unary(
  method evaluate_step_binary (line 151) | fn evaluate_step_binary(
  method evaluate_step (line 403) | fn evaluate_step(&self, context: &HashMap<String, Self>) -> Result<Self,...
  method evaluate (line 608) | pub fn evaluate(&self, context: &HashMap<String, Self>) -> Result<Self, ...
  function t (line 629) | fn t(expression: &str, result: &str) {
  function arithmetic (line 642) | fn arithmetic() {
  function linear_algebra (line 704) | fn linear_algebra() {
  function indices (line 725) | fn indices() {
  function logic (line 736) | fn logic() {
  function comparisons (line 752) | fn comparisons() {

FILE: savage_core/src/expression.rs
  type Function (line 15) | pub type Function =
  type Integer (line 19) | pub type Integer = num::bigint::BigInt;
  type Rational (line 22) | pub type Rational = num::rational::Ratio<Integer>;
  type Complex (line 25) | pub type Complex = num::complex::Complex<Rational>;
  type Vector (line 28) | pub type Vector = nalgebra::DVector<Expression>;
  type Matrix (line 31) | pub type Matrix = nalgebra::DMatrix<Expression>;
  type RationalRepresentation (line 35) | pub enum RationalRepresentation {
    method merge (line 46) | pub(crate) fn merge(self, other: Self) -> Self {
  type Expression (line 60) | pub enum Expression {
    method typ (line 155) | pub(crate) fn typ(&self) -> Type {
    method precedence_and_associativity (line 197) | pub(crate) fn precedence_and_associativity(&self) -> (isize, Associati...
    method precedence (line 261) | pub(crate) fn precedence(&self) -> isize {
    method associativity (line 268) | pub(crate) fn associativity(&self) -> Associativity {
    method parts (line 275) | pub(crate) fn parts(&self) -> Vec<Self> {
    method variables (line 339) | pub fn variables(&self) -> HashSet<String> {
  type Type (line 123) | pub(crate) enum Type {
  type Associativity (line 144) | pub(crate) enum Associativity {

FILE: savage_core/src/functions/combinatorics.rs
  function factorial (line 22) | fn factorial(n: NonNegativeInteger) -> Integer {

FILE: savage_core/src/functions/linear_algebra.rs
  function determinant (line 21) | fn determinant(matrix: SquareMatrix) -> Expression {

FILE: savage_core/src/functions/logic.rs
  function and (line 20) | fn and(a: bool, b: bool) -> bool {

FILE: savage_core/src/functions/mod.rs
  type NonNegativeInteger (line 19) | pub(crate) type NonNegativeInteger = Integer;
  type PositiveInteger (line 24) | pub(crate) type PositiveInteger = Integer;
  type SquareMatrix (line 29) | pub(crate) type SquareMatrix = Matrix;
  type Parameter (line 33) | pub enum Parameter {
  type Metadata (line 58) | pub struct Metadata {
  type Function (line 72) | pub struct Function {
  function wrap_proxy (line 81) | fn wrap_proxy(
  function functions (line 143) | pub fn functions() -> Vec<Function> {
  function function_expression (line 156) | pub fn function_expression(name: &str) -> Option<Expression> {
  function t (line 176) | fn t(expression: &str, result: &str) {
  function examples (line 189) | fn examples() {

FILE: savage_core/src/functions/number_theory.rs
  function is_prime (line 30) | fn is_prime(n: NonNegativeInteger) -> Expression {
  function nth_prime (line 52) | fn nth_prime(n: PositiveInteger) -> Expression {
  function prime_pi (line 75) | fn prime_pi(n: NonNegativeInteger) -> Expression {

FILE: savage_core/src/helpers.rs
  type Output (line 17) | type Output = Self;
  method neg (line 19) | fn neg(self) -> Self {
  type Output (line 25) | type Output = Self;
  method not (line 27) | fn not(self) -> Self {
  type Output (line 33) | type Output = Self;
  method add (line 35) | fn add(self, other: Self) -> Self {
  method add_assign (line 41) | fn add_assign(&mut self, other: Self) {
  type Output (line 47) | type Output = Self;
  method sub (line 49) | fn sub(self, other: Self) -> Self {
  method sub_assign (line 55) | fn sub_assign(&mut self, other: Self) {
  type Output (line 61) | type Output = Self;
  method mul (line 63) | fn mul(self, other: Self) -> Self {
  method mul_assign (line 69) | fn mul_assign(&mut self, other: Self) {
  type Output (line 75) | type Output = Self;
  method div (line 77) | fn div(self, other: Self) -> Self {
  method div_assign (line 83) | fn div_assign(&mut self, other: Self) {
  type Output (line 89) | type Output = Self;
  method rem (line 91) | fn rem(self, other: Self) -> Self {
  method rem_assign (line 97) | fn rem_assign(&mut self, other: Self) {
  method from (line 103) | fn from(expression: &Self) -> Self {
  method from (line 109) | fn from(integer: Integer) -> Self {
  type Error (line 115) | type Error = Expression;
  method try_from (line 117) | fn try_from(expression: Expression) -> Result<Self, Self::Error> {
  method from (line 131) | fn from(rational: Rational) -> Self {
  type Error (line 137) | type Error = Expression;
  method try_from (line 139) | fn try_from(expression: Expression) -> Result<Self, Self::Error> {
  method from (line 153) | fn from(complex: Complex) -> Self {
  type Error (line 159) | type Error = Expression;
  method try_from (line 161) | fn try_from(expression: Expression) -> Result<Self, Self::Error> {
  method from (line 171) | fn from(vector: Vector) -> Self {
  type Error (line 177) | type Error = Expression;
  method try_from (line 179) | fn try_from(expression: Expression) -> Result<Self, Self::Error> {
  method from (line 193) | fn from(matrix: Matrix) -> Self {
  type Error (line 199) | type Error = Expression;
  method try_from (line 201) | fn try_from(expression: Expression) -> Result<Self, Self::Error> {
  method from (line 211) | fn from(boolean: bool) -> Self {
  type Error (line 217) | type Error = Expression;
  function try_from (line 219) | fn try_from(expression: Expression) -> Result<Self, Self::Error> {
  function var (line 229) | pub fn var(identifier: impl Into<String>) -> Expression {
  function fun (line 234) | pub fn fun(function: impl Into<Expression>, arguments: impl Into<Vec<Exp...
  function int (line 239) | pub fn int(integer: impl Into<Integer>) -> Expression {
  function rat (line 245) | pub fn rat(numerator: impl Into<Integer>, denominator: impl Into<Integer...
  function ratd (line 256) | pub fn ratd(numerator: impl Into<Integer>, denominator: impl Into<Intege...
  function com (line 266) | pub fn com(
  function comd (line 286) | pub fn comd(
  function pow (line 302) | pub fn pow(base: impl Into<Expression>, exponent: impl Into<Expression>)...
  function eq (line 307) | pub fn eq(left: impl Into<Expression>, right: impl Into<Expression>) -> ...
  function ne (line 312) | pub fn ne(left: impl Into<Expression>, right: impl Into<Expression>) -> ...
  function lt (line 317) | pub fn lt(left: impl Into<Expression>, right: impl Into<Expression>) -> ...
  function le (line 322) | pub fn le(left: impl Into<Expression>, right: impl Into<Expression>) -> ...
  function gt (line 327) | pub fn gt(left: impl Into<Expression>, right: impl Into<Expression>) -> ...
  function ge (line 332) | pub fn ge(left: impl Into<Expression>, right: impl Into<Expression>) -> ...
  function and (line 337) | pub fn and(a: impl Into<Expression>, b: impl Into<Expression>) -> Expres...
  function or (line 342) | pub fn or(a: impl Into<Expression>, b: impl Into<Expression>) -> Express...

FILE: savage_core/src/parse.rs
  type Error (line 14) | pub type Error = chumsky::error::Simple<char, Range<usize>>;
  type ErrorReason (line 17) | pub type ErrorReason = chumsky::error::SimpleReason<char, Range<usize>>;
  function parser (line 25) | pub fn parser() -> impl Parser<char, Expression, Error = Error> {
  type Err (line 241) | type Err = Vec<Error>;
  method from_str (line 243) | fn from_str(string: &str) -> Result<Self, Self::Err> {
  function t (line 256) | fn t(string: &str, expression: Expression) {
  function variables (line 261) | fn variables() {
  function functions (line 268) | fn functions() {
  function integers (line 287) | fn integers() {
  function rational_numbers (line 295) | fn rational_numbers() {
  function vectors (line 303) | fn vectors() {
  function matrices (line 318) | fn matrices() {
  function booleans (line 338) | fn booleans() {
  function operators (line 344) | fn operators() {
  function benchmark (line 389) | fn benchmark() {

FILE: savage_core/src/print.rs
  function decimal_representation (line 13) | fn decimal_representation(x: &Rational) -> Option<(Integer, usize)> {
  method fmt_prefix (line 43) | fn fmt_prefix(&self, f: &mut Formatter<'_>, symbol: &str, a: &Self) -> R...
  method fmt_infix (line 57) | fn fmt_infix(&self, f: &mut Formatter<'_>, symbol: &str, a: &Self, b: &S...
  method fmt (line 82) | fn fmt(&self, f: &mut Formatter<'_>) -> Result {
  function t (line 247) | fn t(expression: Expression, string: &str) {
  function variables (line 252) | fn variables() {
  function functions (line 259) | fn functions() {
  function integers (line 275) | fn integers() {
  function rational_numbers (line 286) | fn rational_numbers() {
  function complex_numbers (line 310) | fn complex_numbers() {
  function vectors (line 336) | fn vectors() {
  function matrices (line 351) | fn matrices() {
  function booleans (line 372) | fn booleans() {
  function operators (line 378) | fn operators() {

FILE: savage_core/src/simplify.rs
  method simplify (line 13) | pub(crate) fn simplify(&self) -> Self {
  function t (line 186) | fn t(expression: &str, result: &str) {
  function arithmetic (line 198) | fn arithmetic() {
  function logic (line 235) | fn logic() {
  function comparisons (line 256) | fn comparisons() {

FILE: savage_macros/src/lib.rs
  type Arguments (line 13) | struct Arguments {
  function function (line 23) | pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
  function functions (line 93) | pub fn functions(input: TokenStream) -> TokenStream {
Condensed preview — 29 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (193K chars).
[
  {
    "path": ".github/dependabot.yml",
    "chars": 278,
    "preview": "# Please see the documentation for all configuration options:\n# https://docs.github.com/github/administering-a-repositor"
  },
  {
    "path": ".github/workflows/continuous_integration.yml",
    "chars": 1829,
    "preview": "# Based on https://github.com/actions-rs/meta/blob/master/recipes/msrv.md\n\non: [push, pull_request]\n\nname: Continuous in"
  },
  {
    "path": ".gitignore",
    "chars": 8,
    "preview": "/target\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 1322,
    "preview": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Change"
  },
  {
    "path": "Cargo.toml",
    "chars": 156,
    "preview": "[workspace]\nmembers = [\n    \"savage_macros\",\n    \"savage_core\",\n    \"savage\",\n]\n\n[profile.release]\ncodegen-units = 1\nopt"
  },
  {
    "path": "LICENSE",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 9869,
    "preview": "# Savage Computer Algebra System\n\nSavage is a new computer algebra system written from scratch in pure Rust.\nIts goals a"
  },
  {
    "path": "savage/Cargo.toml",
    "chars": 563,
    "preview": "[package]\nname = \"savage\"\nversion = \"0.2.0\"\nauthors = [\"Philipp Emanuel Weidmann <pew@worldwidemann.com>\"]\ndescription ="
  },
  {
    "path": "savage/help/footer.md",
    "chars": 725,
    "preview": "## License\n\nCopyright (C) 2021-2022  Philipp Emanuel Weidmann (**pew@worldwidemann.com**)\n\nThis program is free software"
  },
  {
    "path": "savage/help/header.md",
    "chars": 2902,
    "preview": "# Savage Computer Algebra System\n\nSavage is a new computer algebra system written from scratch in pure Rust. Its goals a"
  },
  {
    "path": "savage/src/command.rs",
    "chars": 2966,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage/src/help.rs",
    "chars": 3929,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage/src/input.rs",
    "chars": 5665,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage/src/main.rs",
    "chars": 12420,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/Cargo.toml",
    "chars": 484,
    "preview": "[package]\nname = \"savage_core\"\nversion = \"0.2.0\"\nauthors = [\"Philipp Emanuel Weidmann <pew@worldwidemann.com>\"]\ndescript"
  },
  {
    "path": "savage_core/src/evaluate.rs",
    "chars": 30068,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/expression.rs",
    "chars": 12675,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/functions/combinatorics.rs",
    "chars": 663,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/functions/linear_algebra.rs",
    "chars": 1545,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/functions/logic.rs",
    "chars": 536,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/functions/mod.rs",
    "chars": 6742,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/functions/number_theory.rs",
    "chars": 2178,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/helpers.rs",
    "chars": 10244,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/lib.rs",
    "chars": 238,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/parse.rs",
    "chars": 13179,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/print.rs",
    "chars": 15729,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_core/src/simplify.rs",
    "chars": 7443,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  },
  {
    "path": "savage_macros/Cargo.toml",
    "chars": 438,
    "preview": "[package]\nname = \"savage_macros\"\nversion = \"0.1.0\"\nauthors = [\"Philipp Emanuel Weidmann <pew@worldwidemann.com>\"]\ndescri"
  },
  {
    "path": "savage_macros/src/lib.rs",
    "chars": 4604,
    "preview": "// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2021-2022  Philipp Emanuel Weidmann <pew@worldwidemann.co"
  }
]

About this extraction

This page contains the full source code of the p-e-w/savage GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 29 files (179.6 KB), approximately 42.8k tokens, and a symbol index with 156 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!